Q:

What is the purpose of realloc( )?

0

What is the purpose of realloc( )?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer:

The realloc function is used to resize the allocated block of the memory. It takes two arguments first one is a pointer to previously allocated memory and the second one is the newly requested size. The realloc function first deallocates the old object and allocates again with the newly specified size. If the new size is lesser than the old size, the contents of the newly allocated memory will be the same as prior but if any bytes in the newly created object goes beyond the old size, the values of the object will be indeterminate.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{
    char *pcBuffer = NULL;
    /* Initial memory allocation */
    pcBuffer = malloc(8);
    strcpy(pcBuffer, "aticle");
    printf("pcBuffer = %s\n", pcBuffer);
    /* Reallocating memory */
    pcBuffer = realloc(pcBuffer, 15);
    strcat(pcBuffer, "world");
    printf("pcBuffer = %s\n", pcBuffer);
    free(pcBuffer);
    return 0;
}

Output:

pcBuffer = aticle
pcBuffer = aticleworld

Note: It should only be used for dynamically allocated memory but if ptr is the null pointer, realloc behaves like the malloc function.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

What is static memory allocation and dynamic memor... >>
<< How can you determine the size of an allocated por...