2012-10-13 44 views
0

更新:我可以在我的代码中使用strcpy。将指针的值复制到程序集中的另一个新指针

我试图编写一个在x86汇编(att语法)中的strdup的实现,将C中的代码转换为Assembly中的代码。

代码在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. 

    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 @@#$$”。 我想我正在做一些错误的movl,不知道是什么。

p/s:我很确定我的strlen有效。

第2部分: 我写的代码会传回一个指向调用者的指针吗?就像能够释放后来分配的空间一样。

+0

因为你4个字吧,我怀疑你拷贝一个指针 - (字处理)大小的区域,而不是整个字符串, 一世。即在某些地方,你会让指针与数组混淆(除了这里比C更有害)。 – 2012-10-13 15:13:55

+0

我猜你的原型是这样的: 因为movl(%ecx),%ecx mystrcpy(char * src,char ** dest),因为它与strcpy不完全相同,也许你应该写出C代码首先,并将其添加到您的问题 –

+0

您不需要为'strcpy()'或'strlen()'分配任何内存。你停止读取/写入值为0的字节后。 –

回答

0

随着有点生疏汇编技能就应该是这样的:

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  
+0

那么代码的作品,但如果我释放新的char *后释放原始char *,我得到一个错误,说它已被释放。 – rlhh

+0

它不用调用例程就可以很好地释放它?尝试在例程之前和之后打印指针值。我不知道你的确切目标和ABI是什么,我只是复制了原文的样式,并保存了所有额外的注册表 –

相关问题