x86函数在C中返回char *

问题描述 投票:0回答:1

我想在x86中编写一个将从C程序调用的函数。该函数应如下所示:

char *remnth(char *s, int n);

我希望它从字符串s中删除第n个字母并返回该字符串。这是我的remnth.s文件:

section.text
global remnth

remnth:
; prolog
    push ebp
    mov ebp, esp

; procedure
    mov eax, [ebp+8]; Text in which I'm removing every nth letter
    mov ebx, [ebp+12]; = n
    mov ecx, [ebp+8] ; pointer to next letter (replacement)


lopext:
    mov edi, [ebp+12]     ; edi = n  //setting counter
    dec edi               ; edi--  //we don't go form 'n' to '1' but from 'n-1' to '0'
lop1:
    mov cl, [ecx]         ; letter which will be a replacement
    mov byte [eax], cl    ; replace
    test cl,cl            ; was the replacement equal to 0?
    je exit               ; if yes that means the function is over
    inc eax               ; else increment pointer to letter which will be replaced
    inc ecx               ; increment pointer to letter which is a replacement
    dec edi               ; is it already nth number?
    jne lop1              ; if not then repeat the loop
    inc ecx               ; else skip that letter by proceeding to the next one
    jmp lopext            ; we need to set counter (edi) once more 

exit:
; epilog

    pop ebp     
    ret   

问题是,当我从C中的main()调用此函数时,出现分段错误(内核已转储)

据我所知,这与指针高度相关,在这种情况下,我将返回*char,由于我已经看到一些返回int的函数并且它们工作得很好,所以我怀疑我忘记了一些东西正确返回*char很重要。

这是我的C文件的外观:

#include <stdio.h>

extern char *remnth(char *s,int n);

int main()
{
    char txt[] = "some example text\0";

    printf("orginal = %s\n",txt);
    printf("after = %s\n",remnth(txt,3));

    return 0;
}

任何帮助将不胜感激。

c assembly x86 nasm inline-assembly
1个回答
0
投票

您将ecx用作指针,并将cl用作工作寄存器。由于clecx的低8位,因此您正在使用mov cl, [ecx]指令破坏指针。您需要更改一个或另一个。通常,al /ax/eax/ rax用于临时工作寄存器,因为对累加器的某些访问使用较短的指令序列。如果将al用作工作寄存器,则要避免将eax用作指针,而应使用其他寄存器(记住,如有必要请保留其内容)。

© www.soinside.com 2019 - 2024. All rights reserved.