2.6. Memory Allocation in the Heap

Header file <stdlib.h> describes functions malloc and free.

Expression

 malloc(sizeof(T))
allocates enough memory to store one object of type T, and yields the address of that memory.

Note: malloc returns a result of type void*. You normally cast it to a desired type. For example,

  Widget* p = (Widget*) malloc(sizeof(Widget));
allocates memory for a Widget.


Memory deallocation in the heap

Recall that you are required to deallocate memory in the heap manually. Statement

 free(p);
frees the memory pointed to by p, which must be a pointer that was returned by malloc.