totn C Functions

C Language: realloc function
(Resize Memory Block)

In the C Programming Language, the realloc function is used to resize a block of memory that was previously allocated. The realloc function allocates a block of memory (which be can make it larger or smaller in size than the original) and copies the contents of the old block to the new block of memory, if necessary.

Syntax

The syntax for the realloc function in the C Language is:

void *realloc(void *ptr, size_t size);

Parameters or Arguments

ptr
The old block of memory.
size
The size of the elements in bytes.

Note

Returns

The realloc function returns a pointer to the beginning of the block of memory. If the block of memory can not be allocated, the realloc function will return a null pointer.

Required Header

In the C Language, the required header for the realloc function is:

#include <stdlib.h>

Applies To

In the C Language, the realloc function can be used in the following versions:

  • ANSI/ISO 9899-1990

realloc Example

Let's look at an example to see how you would use the realloc function in a C program:

/* Example using realloc by TechOnTheNet.com */

/* The size of memory allocated MUST be larger than the data you will put in it */

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

int main(int argc, const char * argv[])
{
    /* Define required variables */
    char *ptr1, *ptr2;
    size_t length1, length2;

    /* Define the amount of memory required */
    length1 = 10;
    length2 = 30;

    /* Allocate memory for our string */
    ptr1 = (char *)malloc(length1);

    /* Check to see if we were successful */
    if (ptr1 == NULL)
    {
        /* We were not successful, so display a message */
        printf("Could not allocate required memory\n");

        /* And exit */
        exit(1);
    }

    /* Copy a string into the allocated memory */
    strcpy(ptr1, "C malloc");

    /* Oops, we wanted to say more but now do not
     have enough memory to store the message! */

    /* Expand the available memory with realloc */
    ptr2 = (char *)realloc(ptr1, length2);

    /* Check to see if we were successful */
    if (ptr2 == NULL)
    {
        /* We were not successful, so display a message */
        printf("Could not re-allocate required memory\n");

        /* And exit */
        exit(1);
    }

    /* Add the rest of the message to the string */
    strcat(ptr2, " at TechOnTheNet.com");

    /* Display the complete string */
    printf("%s\n", ptr2);

    /* Free the memory we allocated */
    free(ptr2);

    return 0;
}

Similar Functions

Other C functions that are similar to the realloc function: