【发布时间】:2022-01-04 19:44:50
【问题描述】:
我目前正在尝试将汇编函数链接到我的 C 代码驱动程序以完成大学作业。在执行程序时,我得到一个 seg fault 错误。
下面将包括我的 C 文件、ASM 文件中的内容以及来自 GDB 调试器的信息。
C 代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void add(char*, char*); //would extern be needed here maybe?
int main(){
int choice;
char num1[3];
char num2[3];
printf("Welcome to the back and forth program!\n\n");
do{
printf("What would you like to do?\n\n");
printf("1. Add two numbers together.\n");
printf("2. Find if a string is a palindrome. (ASM Version)\n");
printf("3. Find the factorial of a number.\n");
printf("4. Find if a string is a palindrome. (C Version)\n");
printf("5. Exit Program.\n\n");
printf("choose 1-5: ");
scanf("%d", &choice);
getchar();
while(choice < 1 || choice > 5){
printf("\nPlease choose an option between 1 and 5.\n");
scanf("%d", &choice);
getchar();
}
switch(choice){
case 1:
printf("\n*Add two numbers together*\n\n");
printf("Please enter a number: ");
fgets(num1, 1024, stdin);
num1[strlen(num1) - 1] = '\0';
printf("\nPlease enter a second number: ");
fgets(num2, 1024, stdin);
num2[strlen(num2) - 1] = '\0';
add(num1, num2);
printf("\nResult: %s\n", num2);
case 2:
case 3:
case 4:
case 5:
printf("\nThanks for using!\n");
break;
}
}while(choice != 5);
return 0;
}
这里需要注意的一点是,我的教授特别说明我将这两个数字作为字符串读取,然后在汇编中使用atoi() 函数将字符串转换为int。
现在,我的 ASM 代码:
BITS 32
GLOBAL add
EXTERN atoi
section .data
section .bss
section .text
add:
push ebp
mov ebp, esp
push eax
call atoi
push ebx
call atoi
mov eax, [ebp+8]
mov ebx, [ebp+12]
add eax, ebx
pop ebx
ret
由于我需要从我的 Assembly 函数中调用 atoi(),因此我认为有必要使用堆栈。
最后,GDB 调试器在说什么:
Program received signal SIGSEGV, Segmentation fault. 0xffffcdbc in ?? ()
关于调试器错误的说明:在单步执行程序时,一旦到达add(num1, num2),就会出现此错误。
对于其他一些重要信息,我正在使用 GCC 编译器、NASM 编译器、Intel Assembler i386,并通过 VirtualBox 在虚拟机中运行 Debian 10 x86_64。
任何关于此事的帮助将不胜感激!
【问题讨论】:
-
pop ebx可能是pop ebp的拼写错误?