gcc的返回值

来源:互联网 发布:沉迷网络 大学生 事例 编辑:程序博客网 时间:2024/06/14 12:55

不加-Wall参数的情况或多路返回情况下,gcc默认不对未写返回语句的情况作处理。如:

int func()

{

}

int main(void)

{

printf("%d\n", func());

}

编译正常。

一般来说,如果返回值在四个字节以内,就会使用eax寄存器返回。而return语句就是将返回值写入eax。调用者到eax寄存器中取返回值。

因此,在缺失return语句时,返回值是不确定的,危险


汇编代码如下:

(gdb) disassemble main
Dump of assembler code for function main:
   0x08048421 <+0>:    push   %ebp
   0x08048422 <+1>:    mov    %esp,%ebp
   0x08048424 <+3>:    and    $0xfffffff0,%esp
   0x08048427 <+6>:    sub    $0x10,%esp
   0x0804842a <+9>:    call   0x804841c <func>
   0x0804842f <+14>:    mov    %eax,0x4(%esp)-------------------取func的返回值
   0x08048433 <+18>:    movl   $0x80484e0,(%esp)
   0x0804843a <+25>:    call   0x80482f0 <printf@plt>
   0x0804843f <+30>:    mov    $0x0,%eax----------------------------main函数的返回值
   0x08048444 <+35>:    leave  
   0x08048445 <+36>:    ret    
End of assembler dump.

(gdb) disassemble func
Dump of assembler code for function func:
   0x0804841c <+0>:    push   %ebp
   0x0804841d <+1>:    mov    %esp,%ebp
   0x0804841f <+3>:    pop    %ebp
   0x08048420 <+4>:    ret-------------------------------------------------返回之前,未写返回值   
End of assembler dump.