内存:编译器如何选择存储变量的位置? [英] Memory: how does the compiler choose where to store variables?

查看:165
本文介绍了内存:编译器如何选择存储变量的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定两个函数func1和f2,具有以下签名:

Given two functions, func1 and f2, with the following signatures:

void func1(){
    int baba = 12345;
    // printf the value of baba here
}

void f2(){
    int loo;
    //printf the value of loo here
}

... if我运行我的int main,只有func1然后f2:

...if I run my int main, which only has func1 then f2:

int main(){
      func1();
      f2();
}

...那么baba和loo的打印值都将是12345。所以我的问题如下:

...then the printed value of both baba and loo will be 12345. So my question is as follows:


  1. 这是定义的行为还是只是我的机器有错误?

  1. Is this defined behaviour, or just something erroneous that my machine does?

如果这不是我电脑做的一些错误,你能解释为什么编译器选择存储 loo baba相同的地址?

If this isn't some erroneous thing my computer did, can you explain why the compiler chooses to store loo in the same address as baba?

I guess I should ask, if I have these EXACT two functions, will baba and loo have the same value on ANY machine?

我知道loo的价值是什么?

I understand loo's value is the result of baba's leftover bits, and I understand that (on my machine, at least) the stacks of both are being laid out such that loo overlaps onto baba's old territory. Is it true that every machine would lay these two function stacks out in such a manner that baba and loo overlap? Using these two functions exactly as written, that is...

推荐答案

f2 code>, lolo 未初始化。因此,其内容为未定义

In f2(), lolo is uninitialized. It's content is hence undefined.

然而,大多数情况下,内容似乎是堆栈上的数据。通过巧合,你首先调用 func1(),它具有与 f2()。因此,通过偶然变量包含先前存储在相同位置的数据。

Most often however, the content appears to be the data that was on the stack. By coincidence, you've first called func1(), which has exactly the same memory/stack layout than f2(). So by chance the variable contains the data that was previously stored at the same place.

这种行为根本不能保证。它只在这个特定的上下文中工作,因为在这两个调用之间没有创建其他局部变量,没有其他函数调用用其他内容覆盖数据(并且这两个函数具有完全相同的内存布局)。

This behavior is not guaranteed at all. It only appears to work in this specific context because no other local variables were created between the two calls, and no other function call overwrites the data with other content (and the two functions have exactly the same memory layout).

这里有一个小图片来解释这种情况下的情况:

Here a small picture to explain the situation in this specific case:

这篇关于内存:编译器如何选择存储变量的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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