问题描述
我有一个函数,在函数中,我有两个变量
I have a function and in the function, I have two variables,
int auth_flag = 0;
char buffer[16];
现在这是gdb命令x/s buffer
0xffffd01c: "\201\203\004\b\344\203\373\367\002"
和print &auth_flag
$1 = (int *) 0xffffd018
现在,我们从输出中看到,auth_flag的位置在缓冲区之前4个字节.现在,如果我这样声明变量
Now , we see from the output that, location of auth_flag is 4 bytes before buffer. Now, If I declare the variables like this
char buffer[16];
int auth_flag = 0;
先前命令的输出是
0xffffd00c: "\201\203\004\b\344\203\373\367\002" and
$1 = (int *) 0xffffd008
同一件事.后面有100个字节,但顺序是相同的.我的qs是,当我颠倒了变量声明时,为什么在gcc中没有将变量的地址顺序颠倒.我正在读一本书,据说该地址应该颠倒,但我的电脑上没有发生.所以我真的很困惑.
The same thing. 100 bytes behind but the order is same. My qs is, As I have reversed the variable declaration, Why didn't in gcc the address order of the variable is reversed. I am reading a book where it is said that the address ought to be reversed, But it isn't happening in my pc. So I am really confused.
推荐答案
如果说自动变量在标准C或C ++中彼此之间具有任何特定的地址关系,则可以焚烧这本书. struct
或class
中的字段具有实现定义的布局.自动变量甚至都不保证会分配给内存.
Burn that book if it says that automatic variables have any particular address relationship to each other in standard C or C++. Fields in a struct
or class
have an implementation defined layout. Automatic variables aren't even guaranteed to be allocated to memory.
现在,C ++ 要做的保证是定义符号的顺序(编译时构造,而不是内存布局问题)以及构造函数的调用顺序.例如,该顺序精确定义了以下代码的含义:
Now, what C++ does guarantee is the order in which symbols become defined (a compile time construct, not a memory layout issue), and what order constructors get invoked in. For example, that order defines what the following code means in a precise manner:
int foo(int x)
{
int y = x; // this sees the argument x
int x = 3; // this defines an automatic variable named x that shadows the argument
return x + y;
}
C ++还对对象的构造和破坏顺序进行了保证. (当它们按外观顺序进入作用域时构造,当它们离开作用域时按相反的构造顺序破坏.)但是,我不会对此进行深入探讨,因为这超出了您的问题.
C++ also places guarantees on the order of construction and destruction for objects. (Constructed when they come into scope in order of appearance, destructed in reverse order of construction as they leave scope.) But, I won't dig deeply into that, since that goes beyond your question.
这篇关于互换声明的变量具有相同的内存地址模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!