Pointers 将指针的值复制到程序集中的另一个新指针
更新:允许我在代码中使用strcpy 我正试图用x86汇编语言(att语法)编写一个strdup的实现,将C语言中的代码转换为汇编语言中的代码 C代码:Pointers 将指针的值复制到程序集中的另一个新指针,pointers,assembly,att,Pointers,Assembly,Att,更新:允许我在代码中使用strcpy 我正试图用x86汇编语言(att语法)编写一个strdup的实现,将C语言中的代码转换为汇编语言中的代码 C代码: char* func( int x, char* name){ namestr = (char *) malloc( strlen(name) + 1 ); strdup( namestr, name ); free( name ); //Just showing what I plan to do later.
char* func( int x, char* name){
namestr = (char *) malloc( strlen(name) + 1 );
strdup( namestr, name );
free( name ); //Just showing what I plan to do later.
return namestr;
}
程序集中的代码:
;basic start, char* I'm trying to copy is at 12(%ebp)
new_string:
pushl %ebp
movl %esp, %ebp
pushl %edi
subl $20, %esp
movl 12(%ebp), %ecx
movl %ecx, %edi
movl (%ecx), %ecx
movl %ecx, -8(%ebp)
;get the length of the string + 1, allocate space for it
.STR_ALLOCATE:
movl $0, %eax
movl $-1, %ecx
repnz scasb
movl %ecx, %eax
notl %eax
subl $1, %eax
addl $1, %eax
movl %eax, (%esp)
call malloc
movl %eax, -12(%ebp)
;copy value of of the char* back to %eax, save it to the stack, pass the address back
.STR_DUP:
movl -8(%ebp), %eax
movl %eax, -12(%ebp)
leal -12(%ebp), %eax
.END:
popl %edi
leave
ret
当我运行代码时,我只得到一部分字符*返回。
示例:传入“堆栈溢出”将得到“Stac@@@#$$”。
我猜我的电影有问题,不知道是什么
附言:我很确定我的strlen能用
第2部分:
我写的代码会传回一个指向调用者的指针吗?就像我能够释放我以后分配的任何空间一样 有点生疏的汇编技巧,它看起来是这样的:
pushl %ebp
movl %esp, %ebp
pushl %edi
pushl %esi
subl $20, %esp
movl 12(%ebp), %edi
;get the length of the string + 1, allocate space for it
.STR_ALLOCATE:
; next is dangerous. -1 is like scan "forever". You might want to set a proper upper bound here, like in "n" string variants.
movl $-1, %ecx
repnz scasb
notl %ecx
; subl $1, %ecx
; addl $1, %ecx
movl %ecx, -8(%ebp)
pushl %ecx
call malloc
add $4,%esp
movl %eax, -12(%ebp)
movl -8(%ebp),%ecx
movl %eax, %edi
movl 12(%ebp).%esi
rep movsb
movl -12(%ebp),%eax
popl %esi
popl %edi
leave
ret
因为您得到了4个字符,所以我怀疑您复制的是指针大小的区域,而不是整个字符串。E在某些地方,你会造成指针与数组的混淆(除了这比在C中更有害)。我猜你的原型是:mystrcpy(char*src,char**dest),因为movl(%ecx),%ecx因为这与strcpy不完全相同,也许你应该先写出C代码,并将其添加到您的问题中您不需要为
strcpy()
或strlen()
分配任何内存。您在值为0的字节后停止读/写。@H2CO3是的,我很确定您是对的,但我自己看不到。@Marcovandevort我已在C中添加了代码。代码可以工作,但如果我在释放新字符*后尝试释放原始字符*,我得到一个错误,说它已经被释放了。它可以释放而不调用例程吗?尝试在例程之前和之后打印指针值。我不知道你的确切目标和ABI是什么,我只是复制了原始的样式,并保存了所有额外的注册表