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

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

问题描述

给定两个功能,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
}

...如果我跑我的INT为主,其中只有FUNC1然后F2:

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

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

...那么这两个马场和厕所的印刷值将是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?

如果这不是一些错误的东西在我的电脑一样,你能解释一下为什么编译器选择厕所存储在同一地址巴巴?

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?

编辑:我想我应该问,如果我有这EXACT两个功能,将粑粑和厕所有任何机器上相同的值

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

我明白厕所的价值是巴巴的边角料的结果,而据我所知,(我的机器上,至少)两者的筹码被布置,使得厕所重叠到巴巴的老领土。的这是真的的每台机器会放下这两个功能,以这样的方式堆叠出粑粑和厕所重叠?使用这两个功能完全相同写入,即...

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()洛洛是初始化。它的内容,因此未定义

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

最常见然而,内容似乎这是堆栈上的数据。巧合的是,你先叫 func1的(),它具有完全相同的内存/堆栈比布局F2()。因此,通过机会变量包含pviously存储在同一个地方$ P $的数据。

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天全站免登陆