运维开发网

在变量赋值之前,内存不包含垃圾

运维开发网 https://www.qedev.com 2020-04-28 10:18 出处:网络 作者:运维开发网整理
我有一个简单的C程序: #include <stdio.h> int main() { int i; for(i = 0; i < 10; i++) printf("Hello\n"); return 0; } 我用gcc编译它: gcc -g test.c 然后我运行调试器: gdb -q ./a.out 我在main设置了一个断点并运行: (gdb)
我有一个简单的C程序:

#include <stdio.h>

int main()
{
    int i;
    for(i = 0; i < 10; i++)
        printf("Hello\n");

    return 0;
}

我用gcc编译它:

gcc -g test.c

然后我运行调试器:

gdb -q ./a.out

我在main设置了一个断点并运行:

(gdb) break main
(gdb) run

然后我让它运行,直到它到达断点并尝试在地址rip当前指向显示汇编指令:

(gdb) x/i $rip
=> 0x400538 <main+8>:   mov    DWORD PTR [rbp-0x4],0x0

看起来下一条指令将用值0初始化我的局部变量i.由于它还没有执行指令,我希望有一个垃圾值.

(gdb) x/4xb $rbp-4
0x7fffffffe0ec: 0x00    0x00    0x00    0x00

它看起来不像垃圾值,看起来一切都已经零了.在执行main中的任何代码之前,断点应该暂停程序.

我在这里错过了什么?在初始化局部变量i之前,该内存位置是否应包含随机垃圾值?

It doesn’t look like garbage values, it looks like everything has already been zero’d out.

我修改了你的例子,以表明它只是一个巧合.

#include <stdio.h>

int main()
{
  int i1;
  int i2;
  int i3;
  int i4;
  int i5;
  int i6;
  int i;

  for(i = 0; i < 10; i++)
    printf("Hello\n");

  return 0;
}
(gdb) start
Temporary breakpoint 1 at 0x4005ac: file main.cpp, line 13.
Starting program: /home/a.out

Temporary breakpoint 1, main () at main.cpp:13
13        for(i = 0; i < 10; i++)
(gdb) info locals
i1 = 0
i3 = 0
i5 = 32767
i = 0
i2 = 4195520
i4 = -7856
i6 = 0

你看,不同的价值是可能的.

至于您的示例,此地址的值在到达main()之前至少更改两次.只需设置监视此地址,您将看到它在main()之前调用的函数中已更改:

(gdb) watch *(int*)0x7fffffffe06c
Hardware watchpoint 1: *(int*)0x7fffffffe06c

(gdb) r
Starting program: /home/a.out
Hardware watchpoint 1: *(int*)0x7fffffffe06c

Old value = 0
New value = 58
0x0000003a1d890880 in handle_intel () from /lib64/libc.so.6


Hardware watchpoint 1: *(int*)0x7fffffffe06c

Old value = 58
New value = 0
0x0000003a1d0146fd in _dl_runtime_resolve () from /lib64/ld-Linux-x86-64.so.2

Hardware watchpoint 1: *(int*)0x7fffffffe06c

Old value = 0
New value = 1
0x00000000004005c3 in main () at main.cpp:7
7         for(i = 0; i < 10; i++)
#0  0x00000000004005c3 in main () at main.cpp:7
0

精彩评论

暂无评论...
验证码 换一张
取 消