The realloc function can be used to change the size of a block of memory that was dynamically allocated. The memory block must have been allocated with either the malloc or the calloc functions. The function returns an address to the reallocated memory block, which can be stored in a pointer to the desired data type.

The realloc function requires two argument. The first argument is the address of the memory block. The second argument, of the type time_t, specifies the size of the memory block that the application is trying to allocate.

The return value of the function is "void *", an it requires a cast to a pointer of the required data type. If the function fails in reallocating memory, the value NULL is returned.

An important feature of realloc is that, if it succeeds, the beginning of the new block of memory will have the same contents as the old memory block. If this cannot be done, a NULL pointer will be returned.

The following code shows an example of realloc in use:

#include <stdlib.h>
#include        <stdio.h>

int main()
        int i;
        int num_elements = 10;
        int *p, *q;
        p = (int *)malloc(sizeof(int)*num_elements);
        for (i=0; i<num_elements; i++) {
                p[i] = i;
        q = (int *)realloc(p, sizeof(int)*num_elements+5);
        for (i=0; i<num_elements; i++) {
                printf("the value is %d\n", q[i]);
        return 0;
Article created on 2008-08-19 22:08:46

Post a comment