How is memory allocated for stack variables?

坚强是说给别人听的谎言 提交于 2019-12-11 06:37:35

问题


On VS (release), I run the following:

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). 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.


回答1:


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.

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)

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



回答2:


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. "123" requires 4 bytes - the extra byte being for the null terminator.




回答3:


Try reversing the order of declaring a[] and b[], and/or increase the length of 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. So, another test would be to add int c and compare those addresses.



来源:https://stackoverflow.com/questions/18181502/how-is-memory-allocated-for-stack-variables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!