/* Allocate original array */ int * pi; if((pi = (int*)malloc( INIT_SZ * sizeof(int))) == NULL) { /* Error handling */ return NULL; } ... /* Allocate larger block of memory */ int * new; if((new = (int*)malloc(2 * INIT_SZ * sizeof(int))) == NULL) { /* Error handling */ free(pi); return NULL; } /* Copy data from original array */ memcpy(new, pi, INIT_SZ*sizeof(int)); /* Free original array */ free(pi); /* Update pointer variable pi */ pi = new;A more concise way to do this is to call the stdlib.h function realloc(), which resizes a block of memory that has already been dynamically allocated:
/* Allocate original array */ int * pi; if((pi = (int*)malloc( INIT_SZ * sizeof(int))) == NULL) { /* Error handling */ return NULL; } ... /* Resize original array: double size */ int * tmp ; if((tmp = (int*)realloc( pi, 2 * INIT_SZ * sizeof(int))) == NULL ) { /* Error handling */ free(pi); return NULL; } pi = tmp;Here, the first argument to realloc() is the block to be resized, and the second argument is the requested size. realloc() returns a pointer to the new block of memory, which may or may not be the same address as the original pointer pi. If the pointers are different, then realloc() will automatically free pi and copy data into the new block of memory.
Like malloc(), realloc() will fail and return NULL if there is not enough memory available to complete the request. This means that you need to be careful when you overwrite the address of the original array. In this example, the value of pointer pi would be lost if this call to realloc() fails:
/* Resize original array: double size */ pi = (int*)realloc(pi, 2 * (*p_size) * sizeof(int))For this reason, it is a good idea to save the return value of realloc() into a temporary variable before you overwrite the original pointer, as shown above with the use of variable tmp.
Type man 3 malloc at the command line for more information on malloc() and realloc().