E.10. Dynamic Memory Allocation with calloc and realloc
In Chapter 10, we discussed C++-style dynamic memory allocation with new and delete. C++ programmers should use new and delete, rather than C's functions malloc and free (header <cstdlib>). However, most C++ programmers will find themselves reading a great deal of C legacy code, and therefore we include this additional discussion on C-style dynamic memory allocation.
The general utilities library (<cstdlib>) provides two other functions for dynamic memory allocationcalloc and realloc. These functions can be used to create and modify dynamic arrays. As shown in Chapter 8, Pointers and Pointer-Based Strings, a pointer to an array can be subscripted like an array. Thus, a pointer to a contiguous portion of memory created by calloc can be manipulated as an array. Function calloc dynamically allocates memory for an array and initializes the memory to zeroes. The prototype for calloc is
void *calloc( size_t nmemb, size_t size );
It receives two argumentsthe number of elements (nmemb) and the size of each element (size)and initializes the elements of the array to zero. The function returns a pointer to the allocated memory or a null pointer (0) if the memory is not allocated.
Function realloc changes the size of an object allocated by a previous call to malloc, calloc or realloc. The original object's contents are not modified, provided that the memory allocated is larger than the amount allocated previously. Otherwise, the contents are unchanged up to the size of the new object. The prototype for realloc is
void *realloc( void *ptr, size_t size );
Function realloc takes two argumentsa pointer to the original object (ptr) and the new size of the object (size). If ptr is 0, realloc works identically to malloc. If size is 0 and ptr is not 0, the memory for the object is freed. Otherwise, if ptr is not 0 and size is greater than zero, realloc TRies to allocate a new block of memory. If the new space cannot be allocated, the object pointed to by ptr is unchanged. Function realloc returns either a pointer to the reallocated memory or a null pointer.
Common Programming Error E.2