global variables not defined contiguously in memory

John (Eljay) Love-Jensen eljay@adobe.com
Thu Mar 5 15:53:00 GMT 2009


Hi mikwilmot,

There is no guarantee in C as to memory layout of global data.

There is no guarantee in GCC for C as to memory layout of global data.

On many platforms, a global specified like this...

int foo;

...will be located in the zero-initialized .bss section.

Whereas a global specified like this...

int bar = 0;

...will be located in the .data section.

So if you have...

int foo;
int bar = 0;

... they will likely not be located next to each other in memory.

To get some sort of memory layout of your globals, you can do this:

struct GlobalData
{
  int foo;
  int bar;
};

struct GlobalData globalData =
{
  0, // foo
  0, // bar
};

Since the globals have been collected together in a struct, now there is some guarantee as to the memory layout of the variables. The foo global variable is guaranteed to be before bar.  Note that there may be alignment padding bytes between foo and bar (probably not on most architectures... but there COULD be...), and that there may be trailing padding bytes in the GlobalData structure (which probably is not interesting in this situation).

Also, string data may be collated together...

char[] quux = "Blah blah";

...and not appear in memory order.

Putting quux in the GlobalStruct would also help with that, with the caveat that you have to specify the array size explicitly.  Note the memory layout implications & difference between char* and char[]!

HTH,
--Eljay



More information about the Gcc-help mailing list