凡变量的值存储在c [英] Where the value of variables are stored in C

查看:101
本文介绍了凡变量的值存储在c的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下code段:

int func()
{
    int a=7;
    return a;
}

是值7保存在可执行文件code段?或者是在数据段或code段?请问答案取决于操作系统或编译器上?

Is the code segment where the value 7 is stored in the executable? Or is it in data segment or in the code segment? Will the answer depends on the Operating system or the compiler?

推荐答案

每个可执行文件格式有一些章节。其中之一是文本,包含装配 - 二进制code。其中之一是,其中的malloc -ed数据被发现,上局部变量的存储位置。有几个人,但现在不重要。以上三种是常见的无处不在。

Each executable format has some sections. One of them is text, contains the assembly - binary code. One of them is heap where malloc-ed data is found and on is stack where local variables are stored. There are several others but it doesn't matter now. The above three are common everywhere.

现在,像你的本地数据驻留在堆栈中。在可执行文件,该值存储在文本部分。

Now, local data like your a resides on the stack. In the executable file, the value is stored in the text section.

我添加了一个到code(返回0),其中 -g 编译然后做 objdump的-CDgS的a.out 键,搜索 0x424242 (我已经更换了你 7 与在code随机发生的)机会较小的值。

I've added a main to your code (returning 0), compiled with -g then did objdump -CDgS a.out and searched for 0x424242 (I've replaced your 7 with a value with lesser chance of randomly occurring in code).

00000000004004ec <func>:
int func()
{
  4004ec:       55                      push   %rbp
  4004ed:       48 89 e5                mov    %rsp,%rbp
        int a=0x42424242;
  4004f0:       c7 45 fc 42 42 42 42    movl   $0x42424242,-0x4(%rbp)
        return a;
  4004f7:       8b 45 fc                mov    -0x4(%rbp),%eax
}
  4004fa:       5d                      pop    %rbp
  4004fb:       c3                      retq 

正如你所见, C7 45 FC 42 42 42 42 表示值存储在生成的文件。实际上,在二进制通过 XXD 看时是这样的话:

As you see, c7 45 fc 42 42 42 42 means that the value is stored in the generated file. Indeed, this is the case when looking at the binary via xxd:

$ xxd a.out | grep 4242
00004f0: c745 fc42 4242 428b 45fc 5dc3 5548 89e5  .E.BBBB.E.].UH..

您可以识别在 XXD 片段上面下线。

You can recognize the above assembly line in the xxd snippet.

这篇关于凡变量的值存储在c的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆