2012-10-13 49 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是什麼,我只是複製了原文的樣式,並保存了所有額外的註冊表 –

相關問題