The heap uses dynamic allocation. Dynamic allocation occurs on run time of the process and is not subject to a limit (such as the stack is). Data in heap is also not necessarily linear like the stack (which is consecutive in memory). Juxtaposed elements in heap are not at all required and are often scattered throughout the RAM. Basically, it searches for unallocated space in RAM and will allocate it manually. There are 3 commands used in dynamic memory allocation.
malloc takes a single parameter. It will allocate size number of bytes. It will return a void pointer that is pointed at the very first byte in the newly allocated memory. Error checking for all dynamic memory allocation is usually done by simply checking if the memory address is NULL.
Code:
calloc(size_t nmemb, size_t size)
Calloc takes two parameters. The second parameter is multiplied by the first parameter. Like malloc, calloc will allocate that number of bytes. However, calloc, unlike malloc, will overwrite all byts with \x00 upon allocation. This is often used for strings to ensure no false data is read. Like malloc, calloc will return a void pointer which points to the first allocated byte.
Code:
realloc(void *ptr, size_t size)
Realloc takes two parameter. It takes a pointer that has already been allocated and the new size to which it will change the allocated size that‟s in the same space in memory without changing the value.
Free is not a dynamic memory allocation function but rather the deallocation function. It takes a single parameter; the pointer of a previously dynamically allocated spot in memory. It will then deallocate the memory and will be able to be used in the future. It is very important to be sure to deallocate all variables in heap.
Examples:
To he addded
-H
Houga@entropy.cat