简体   繁体   English

从NASM函数返回一个char数组

[英]Returning a char array from a NASM function

I'm trying to do the following for the sake of practice in NASM: 为了在NASM中进行实践,我正在尝试执行以下操作:

1)Read a string from command-line in C 1)从命令行在C中读取字符串

2)Pass that string to a NASM function which takes the string as its first parameter 2)将该字符串传递给以该字符串为第一个参数的NASM函数

3)Return that exact string from NASM function 3)从NASM函数返回确切的字符串

prefix.asm: prefix.asm:

;nasm -f elf32 prefix.asm -o prefix.o

segment .bss
pre resb 256

segment .text
global prefix

    prefix:
        push ebp          ;save the old base pointer value
        mov  ebp,esp      ;base pointer <- stack pointer

        mov eax,[ebp+8]   ;function argument

        add esp, 4
        pop ebp
        ret

prefix c: 前缀c:

//nasm -f elf32 prefix.asm -o prefix.o
//gcc prefix.c prefix.o -o prefix -m32
#include <stdio.h>
#include <string.h>

char* prefix(char *str);

int main(void)
{
    char str[256];
    char* pre;
    int a;

    printf("Enter string: ");
    scanf("%s" , str) ;
    pre = prefix(str);
    printf("Prefix array: %s\n", pre);
    return 0;
}

After I run(it compiles w/o any problem) and supply my string to the program I get a Segmentation fault (core dumped) error. 我运行(它编译没有任何问题)并将字符串提供给程序后,出现分段错误(核心转储)错误。

First try to write a C program to implement char* prefix(char *str) , disassemble it and understand it. 首先尝试编写一个C语言程序来实现char* prefix(char *str) ,反汇编并理解它。

Problem 1: the add esp, 4 should be deleted. 问题1: add esp, 4应删除add esp, 4 A function should preserve the stack pointer. 函数应保留堆栈指针。 Ie the esp should be the same before the first instruction and before the return instruction. 即, esp应该在第一条指令之前和返回指令之前相同。 Your assembly code increases esp by 4. 您的汇编代码使esp增加4。

Problem 2: Don't name your .asm and .c to be the same. 问题2:不要将您的.asm.c命名为相同。 Use different names. 使用不同的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM