内存是如何分配堆栈变量? [英] How is memory allocated for stack variables?
问题描述
在VS(释放),我运行以下命令:
On VS (release), I run the following:
int main(void)
{
char b[] = "123";
char a[] = "1234567";
printf("%x %x\n", b,a);
return 0;
}
我可以看到,一对的内存地址为b + 3(字符串的长度)。这表明存储器与没有间隙分配。这保证最少的记忆被使用。
所以,现在我有点相信,所有的编译器将这样做。
我要确保这个猜测这里。有人可以给我一个更正式的证明或告诉我,我的猜测是植根于一个巧合。
I can see that, the mem address of a is b+3(the length of the string). Which shows that the memory are allocated with no gaps. And this guarantee that least memories are used. So, I now kind of believe that all compilers will do so. I want to make sure of this guess here. Can somebody give me an more formal proof or tell me that my guess is rooted on a coincidence.
推荐答案
没有,它不能保证总是会有数据的完美包装。
No, it's not guaranteed that there will always be perfect packing of data.
例如,我编译和拼命地跑在G ++这code,不同的是8。
For example, I compiled and runned this code on g++, and the difference is 8.
您可以阅读更多关于这个 rel=\"nofollow\">。
You can read more about this here.
TL;博士:编译器可以对齐对象在内存中只有某个常数(总是机器字长)地址整除以帮助处理器(对他们来说更容易与这些地址有效)
tl;dr: Compilers can align objects in memory to only addresses divisible by some constant (always machine-word length) to help processor(for them it's easier to work with such addresses)
UPD:大约对准一个有趣的例子:
UPD: one interesting example about alignment:
#include <iostream>
using namespace std;
struct A
{
int a;
char b;
int c;
char d;
};
struct B
{
int a;
int c;
char b;
char d;
};
int main()
{
cout << sizeof(A) << " " << sizeof(B) << "\n";
}
对于我来说,它打印
For me, it prints
16 12
这篇关于内存是如何分配堆栈变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!