一旦C主程序进入主函数,尝试运行GDB并继续获得分段错误。
GDB错误:
Breakpoint 1, main () at binom_main.c:7
7 n=10;
(gdb) s
10 0;
(gdb) s
12 +){
(gdb) s
Program received signal SIGSEGV, Segmentation fault.
0x00000000004005c4 in otherwise ()
(gdb)
我编译了这样的代码:
as binom.s -o binom.o
gcc -S -Og binom_main.c
gcc -c binom_main.s
gcc binom_main.o binom.o -o runtimes
我试图在这里学习如何更有效地使用GDB,但像这样的段错误是非常模糊和限制的。为什么这个段错误是在函数开始的那一刻引起的?我是否错误地链接了这两个文件?
主要:
#include <stdio.h>
unsigned int result,m,n,i;
unsigned int binom(int,int);
int main(){
n=10;
i=0;
for (i=1; i<2;i++){
result = binom(n,i);
printf("i=%d | %d \n", i, result );
}
return 0;
}
子:
.text
.globl binom
binom:
mov $0x00, %edx #for difference calculation
cmp %edi, %esi #m=n?
je equalorzero #jump to equalorzero for returning of value 1
cmp $0x00, %esi #m=0?
je equalorzero
cmp $0x01, %esi #m=1?
mov %esi,%edx
sub %edi, %edx
cmp $0x01, %edx # n-m = 1 ?
je oneoronedifference
jmp otherwise
equalorzero:
add $1, %eax #return 1
call printf
ret
oneoronedifference:
add %edi, %eax #return n
ret
otherwise:
sub $1, %edi #binom(n-1,m)
call binom
sub $1, %esi #binom(n-1,m-1)
call binom
ret
答案 0 :(得分:2)
使用gdb调试asm时,请查看反汇编窗口以及源窗口。 (例如layout asm
/ layout reg
和layout next
,直到获得所需的窗口组合。)请参阅x86标记wiki的底部以获取更多提示和a链接到文档。
你可以使用stepi
(si
)来逐步说明,而不是通过C语句,同时调查你的asm之外的崩溃,因为它在返回之前会破坏某些内容。
这看起来像一个错误:
sub $1, %edi #binom(n-1,m)
call binom
# at this point, %edi no longer holds n-1, and %esi no longer holds m.
# because binom clobbers them. (This is normal)
# as Jester points out, you also don't save the return value (%eax) from the first call anywhere.
sub $1, %esi #binom(n-1,m-1)
call binom
另一个(次要?)错误是:
cmp $0x01, %esi #m=1?
# but then you never read the flags that cmp set
另一个严重错误:
equalorzero:
add $1, %eax #return 1 # wrong: nothing before this set %eax to anything.
# mov $1, %eax # You probably want this instead
ret