HEAP
Last updated
Heap is a memory region allocated to every program. Unlike stack, heap can be dynamically allocated.
The program can "request" and "release" memory from the heap whenever it requires.
This allocated memory is global. it mean that it can be accessed and modified from anywhere within a program. This can be done using pointers to reference the dynamically allocated memory.
Note that the HEAP permits to use largest data than the stack and theses data are accessible from anywhere.
Theses positives points are followed by a significant negative one : the HEAP is slower than the stack.
In C, stdlib.h provides functions to work with the HEAP.
malloc(), used to request the space memory
free(), used to release the space memory
Here is a code example :
// Dynamically allocate 10 bytes
char *buffer = (char *)malloc(10);
strcpy(buffer, "hello");
printf("%s\n", buffer); // prints "hello"
// Frees/unallocates the dynamic memory allocated earlier
free(buffer);Last updated