Robert Bean
Robert Bean

Reputation: 859

How is memory allocated for stack variables?

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.

Upvotes: 1

Views: 198

Answers (3)

Andrey Komarov
Andrey Komarov

Reputation: 353

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

Upvotes: 2

JackCColeman
JackCColeman

Reputation: 3807

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.

Upvotes: 1

simonc
simonc

Reputation: 42175

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.

Upvotes: 2

Related Questions