How are global variables stored in memory?

你。 提交于 2019-12-24 19:04:40

问题


I have code as follow:

#include <stdio.h>
int g_a;
int g_b;
int g_c;

int main()
{
    printf("Hello world\n");
    return 0;
}

And build it with gcc

gcc -o global global.c

Finally, I use objdump to see address of global variables

objdump -t global

And see the result:

00004020 g_b
00004024 g_a
00004028 g_c

Why are global variables stored in addresses like above? I mean global variables should be stored in order g_a, g_b, g_c


回答1:


global variables should be stored in order g_a, g_b, g_c

No, the order in which they're allocated to memory in no way affects whether or not they can be accessed.

If you want them in a specific order, you can do that by putting them in a struct and declaring that, something like:

#include <stdio.h>

typedef struct {
    int g_a;
    int g_b;
    int g_c;
} tOrderGuaranteed;

tOrderGuaranteed myStruct;

int main()
{
    printf("Hello world\n");
    // Use 'myStruct.g_a' rather than 'g_a'.
    return 0;
}

But, as stated, this doesn't seem to buy you much, especially since the compiler is free to insert padding as it sees fit, between and after those members.

Provided you use g_b to access that (original non-struct) variable, and not some weird (undefined behaviour) variant like *(&g_a+1), your code will work fine regardless of how things are laid out in memory.



来源:https://stackoverflow.com/questions/58405571/how-are-global-variables-stored-in-memory

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