Memory Management (C++)

1. Automatic allocation – Stack
Objects created on the stack, will be cleaned up automatically after they have run out of scope. This happens in excact reverse order than they have been created. It has a higher performance then the dynamic allocation, but normally just 1MB of memory.

int answer = 42;

2. Dynamic allocation – Heap
Objects created by keywords like ‘malloc’ or ‘new’ will get allocated on the heap. It doesn’t get cleaned up automatically and needs to be deallocated by the keywords ‘free’ or ‘delete’. That kind of allocation possibly leads to memory leaks, but provides way more memory.

int *answer = calloc(42, sizeof(int));
free(answer);
int *answer = new int(42);
delete answer;

3. Static allocation – Data
Static objects are stored in the data section at statup and they have a lifetime of the application.

static int answer = 42;

4. Code instructions – Text
The machine code instructions are stored in the text segment. Normally they will be loaded on demand.


Further informations:
More details (+ Asm instructions)
Exmple for con-/destruction order