Dynamic Memory
When a program needs to store a huge amount of data in memory, or when the amount of data is nondeterministic 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 formalloc
orfree
with the right arguments passed infree
- deallocates memory
Storing data on the heap
Using C:
// allocates a variable on a STACKint a;
// allocates memory space on a HEAP (for int - 4 bytes) and returns a void pointer to itint *p = (int*)malloc(sizeof(int));*p = 10; // storing data on the HEAP
// clear heap allocationfree(p); // the compiler stores somewhere info on how many bytes were allocated
// array on the HEAPint *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 cast to int*
, because
malloc
returns a void*
pointer.
Using C++:
// allocates a variable on a STACKint a;
// a scalar on a HEAPint *p = new int;*p = 10;delete p;
// an array on a HEAPp = new int[20];delete[] p;