Dynamic Memory
When a program needs to store huge amount of data in memory, or when the amount of data is underterministic at compile time, the heap memory segment is used. It is “unlimited” (unlike the stack).
Heap commands in C
The following functions are used for heap management:
malloc
- allocates memorycalloc
- similar tomalloc
, but a bit more appropriate for arraysrealloc
- resizes allocated memory block; it can be used as a substitute ofmalloc
orfree
with the right arguments passed infree
- deallocates memory
Storing data on the heap
Using C:
// allocates a variable on a STACK
int a;
// allocates memory space on a HEAP (for int - 4 bytes) and returns a void pointer to it
int *p = (int*)malloc(sizeof(int));
*p = 10; // storing data on the HEAP
// clear heap allocation
free(p); // the compiler stores somewhere info how many bytes were allocated
// array on the HEAP
int *p = (int*)malloc(20 * sizeof(int));
*p = 10; // first index (could be p[0] = 10;)
*(p + 1) = 20; // second index
In the example above the result of malloc
is casted to int*
, because
malloc
returns a void*
pointer.
Using C++:
// allocates a variable on a STACK
int a;
// a scalar on a HEAP
int *p = new int;
*p = 10;
delete p;
// an array on a HEAP
p = new int[20];
delete[] p;