Dynamic memory allocation in C

The real power of pointers comes when they are used in conjunction with a heap manager to allow dynamically sized data structures, such as linked lists and trees. In C there are four standard library functions which allow the heap to be manipulated. The library to be included is stdlib.h.
void * calloc(size_t n, size_t el_size);
Allocates a block of memory big enough to hold n elements each of el_size bytes. The area allocated is set to all zeros. If successful a pointer to the start of the area is returned, otherwise NULL.
void * malloc(size_t size);
Allocates a block of memory big of size bytes. The space is not initialised and may contain any values initially. Again a pointer is returned to the start of the area if successful, otherwise NULL.
void free(void * ptr);
Returns the space pointed to by ptr to be returned to the heap. The heap manager may now reuse this space in a future call of calloc or malloc.
void * realloc(void * ptr, size_t size);
Enlarges the space allocated to ptr to size bytes. If possible this is done by extending the current location, but if necessary moves the current contents to the start of a new, larger area. It returns the address of the final area, which may be different from the original. If it has changed, the old area is now returned to the heap and so all pointers to it must be modified by the calling code. Again NULL is returned if the call fails.

The pointer value NULL

NULL is the pointer equivalent of zero. It is an imaginary pointer value which refers to no legal address. It is actually a pointer value with all bits set to zero. NULL is defined in the libraries stdlib.h and stddef.h and so at least one of these must be included in your program's header before you can use NULL.

Since NULL is effectively zero, it can be used in if and while statements as equal to False. Thus its use as the failure return value in these functions, and many others, allows failure to be signalled as False.


Exercises on this section.


Next - void pointers.

Back to Contents page.