realloc function(Resize Memory Block) in C Language – example and detail

In the C Programming Language, the realloc characteristic is used to resize a block of reminiscence that was once earlier allocated. The realloc characteristic allocates a block of reminiscence (which be can make it large or smaller in dimension than the original) and copies the contents of the ancient block to the new block of memory, if necessary.

Syntax

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

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

Parameters or Arguments

ptr The historical block of memory. size The dimension of the factors in bytes.

Note ptr should have been allotted through one of the following features – calloc function, malloc function, or realloc function.

Returns

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

Required Header

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

#include <stdlib.h>

Applies To

In the C Language, the realloc characteristic 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:

calloc function free function malloc function