The realloc() Function in C

Let’s say we have allocated some memory using malloc() and calloc(), but later we find that memory is too large or too small. The realloc() function is used to resize allocated memory without losing old data. It’s syntax is:

Syntax: void *realloc(void *ptr, size_t newsize);

The realloc() function accepts two arguments, the first argument ptr is a pointer to the first byte of memory that was previously allocated using malloc() or calloc() function. The newsize parameter specifies the new size of the block in bytes, which may be smaller or larger than the original size. And size_t is just an alias of unsigned int defined inside stdlib.h header file.

Let’s take an example:

Suppose that sometimes later we want to increase the size of the allocated memory to store 6 more integers. To do that, we have to allocate additional 6 x sizeof(int) bytes of memory. Here is how you will call realloc() function to allocate 6 x sizeof(int) bytes of memory.

If sufficient memory (in this case 6 * sizeof(int) bytes) is available following already used bytes then realloc() function allocates only allocates 6 * sizeof(int) bytes next to already used bytes. In this case, the memory pointed to by ptr doesn’t change. It is important to note that in doing so old data is not lost but newly allocated bytes are uninitialized.

On the hand, if sufficient memory (in this case 6 * sizeof(int) bytes ) is not available following already used bytes then realloc() re-allocates entire 11 * sizeof(int) bytes of memory somewhere else in the heap and copies the content from the old memory block to the new memory block. In this case, address pointed to by ptr changes.

realloc function

If realloc() failed to expand memory as requested then it returns NULL, the data in the old memory remains unaffected.

The following program demonstrates the realloc() function.

Expected Output:

4 thoughts on “The realloc() Function in C

  1. You should always use a temporary variable to hold the result of realloc, because if it fails a NULL pointer is returned, and free() is not called internally, creating a memory leak.

  2. Can this be done with an array that contains structures? , as for example to enlarge ra [10], of the attached code

    struct register_assignment{
    long unsigned class_id;
    char logical_name[16];

Leave a Comment

%d bloggers like this: