Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do global variables contribute to the size of the executable?

Tags:

c

size

vxworks

Does having global variables increase the size of the executable? If yes how? Does it increase only the data section size or also the text section size?

If I have a global variable and initialization as below:

char g_glbarr[1024] = {"jhgdasdghaKJSDGksgJKASDGHKDGAJKsdghkajdgaDGKAjdghaJKSDGHAjksdghJKDG"};

Now, does this add 1024 to data section and the size of the initilization string to text section?

If instead if allocating space for this array statically, if I malloc it, and then do a memcpy, only the data section size will reduce or the text section size also will reduce?

like image 321
Jay Avatar asked Oct 15 '25 15:10

Jay


2 Answers

Yes, it does. Basically compilers store them to data segment. Sometimes if you use a constant char array in you code (like printf("<1024 char array goes here");) it will go to data segment (AFAIK some old compilers /Borland?/ may store it in the text segment). You can force the compiler to put a global variable in a custom section (for VC++ it was #pragma data_seg(<segment name>)).

Dynamic memory allocation doesn't affect data/text segments, since it allocates memory in the heap.

like image 57
khachik Avatar answered Oct 18 '25 03:10

khachik


The answer is implementation-dependent, but for sane implementations this is how it works for variables with static storage duration (global or otherwise):

  • Whenever the variable is initialized, the whole initialized value of the object will be stored in the executable file. This is true even if only the initial part of it is explicitly initialized (the rest is implicitly zero).
  • If the variable is constant and initialized, it will be in the "text" segment, or equivalent. Some systems (modern ELF-based, maybe Windows too?) have a separate "rodata" segment for read-only data to allow it to be marked non-executable, separate from program code.
  • Non-constant initialized variables will be in the "data" segment in the executable, which is mapped into memory in copy-on-write mode by the operating system when the program is loaded.
  • Uninitialized variables (which are implicitly zero as per the standard) will have no storage reserved in the executable itself, but a size and offset in the "bss" segment, which is created at program load-time by the operating system.
  • Such uninitialized variables may be created in a separate read-only "bss"-like segment if they're const-qualified.
like image 36
R.. GitHub STOP HELPING ICE Avatar answered Oct 18 '25 04:10

R.. GitHub STOP HELPING ICE