Wednesday, October 16, 2013

Which memory is used for variables defined globally?

Suppose we need to work with 8MB stack, & wish to use standard C++ arrays.
Is it true, that

const int MX = 10000;int DP[MX][MX];int main() {  printf("%likB\n", (sizeof(DP))>>10);}

uses heap memory, & for that reason does not segfault (as opposed to when DP is declared in main)? Is it different from allocating the memory via new / malloc in main (besides free issues)?

In modern OS’s, the memory used by an executable is split into (usually) five distinct sections:

  • The Code section (also known as text in Linux/Unix systems for hystericalhistorical reasons). This is where your functions “live”. Often moreover used for constant values, such as char *s = "Hello, World";, the “Hello, World!” part is stored in the CODE section.

  • The “Initialized” data section (also known as “data”) – for global (in C & C++ terms static) data that has been given a value, e.g. int x = 42;

  • Uninitialized data, moreover known as BSS, Block Storage section – for global data that is not given a value, & thus initialized to zero. int y; in a global context, or static int status; would fall into this section.

All of the above sections are defined in the executable. Some executables have more sections than this, yet these are the “typical” ones. An example of an “extra” section is a “read-only data” section, which may be used to store for example string data, rather than storing it in the “code” section.

Once the executable is loaded, two more sections are created by the OS:

  • A stack, which is used to hold local variables inside functions, & is moreover used to “get back” to the calling function. The stack is commonly fairly restricted in size, yet nowhere near as small as it used to be – these days, the stack is regularly in the “a few megabytes” size range. My first machine I used, had a stack of 256 bytes (and that was hard-coded). If you wanted more than that, you had to arrange that by making your own software defined stack. Not very pleasant!

  • A heap. This is used for “dynamic allocation” – for example when creating storage for arrays that vary in size depending on program input. The contents of the heap is not known before the program has started to run. In modern systems, the heap starts out with a small size, & is allowed to grow (but there is a limit, if nothing else when the machine itself runs out of memory – yet often the limit may be lower than that from a system configuration, to avoid one application using up all of the memory in the machine).

In the above example, DP is in the “uninitialized data” section.

No comments:

Post a Comment