简体   繁体   English

如何为堆栈变量分配内存?

[英]How is memory allocated for stack variables?

On VS (release), I run the following: 在VS(发行版)上,我运行以下命令:

int main(void)
{
   char b[] = "123";
   char a[] = "1234567";
   printf("%x  %x\n", b,a);
   return 0;
}

I can see that, the mem address of a is b+3(the length of the string). 我可以看到,a的内存地址是b + 3(字符串的长度)。 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. 有人可以给我更正式的证明,还是告诉我我的猜测是出于巧合。

There is no guarantee what addresses will be chosen for each variable. 不能保证为每个变量选择什么地址。 Different processors may have different requirements or preferences for alignment of variables for instance. 例如,不同的处理器对于变量的对齐可能具有不同的要求或偏好。

Also, I hope there were at least 4 bytes between the addresses in your example. 另外,我希望示例中的地址之间至少有4个字节。 "123" requires 4 bytes - the extra byte being for the null terminator. "123"需要4个字节-多余的字节用于空终止符。

No, it's not guaranteed that there will always be perfect packing of data. 不,不能保证始终会有完美的数据打包。

For example, I compiled and runned this code on g++, and the difference is 8. 例如,我在g ++上编译并运行了此代码,区别是8。

You can read more about this here . 您可以在此处了解更多信息。

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) tl; dr:编译器可以将内存中的对象对齐到只能被某个常数整除的地址(始终为机器字长)以帮助处理器(对于它们来说,使用此类地址更容易)

UPD: one interesting example about alignment: UPD:关于对齐的一个有趣示例:

#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

Try reversing the order of declaring a[] and b[], and/or increase the length of b. 尝试颠倒声明a []和b []的顺序,和/或增加b的长度。

You are making a very big assumption about how storage is allocated. 您对存储分配方式做出了非常大的假设。 Depending on your compiler the string literals might get stored in a literal pool that is NOT on the stack. 根据您的编译器,字符串文字可能会存储在不在堆栈中的文字池中。 Yet a[] and b[] do occupy elements on the stack. 但是a []和b []确实占据了堆栈中的元素。 So, another test would be to add int c and compare those addresses. 因此,另一个测试是添加int c并比较这些地址。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM