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:
In the example above the result of malloc
is cast to int*
, because
malloc
returns a void*
pointer.