he realloc function is used to resize the allocated block of memory. It takes two arguments first one is a pointer to previously allocated memory and the second one is the newly requested size.
The calloc function first deallocates the old object and allocates again with the newly specified size. If the new size is lesser to 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 exceeded size will be indeterminate.
Syntax:
void *realloc(void *ptr, size_t size);
Let’s see an example to understand the working of realloc in C language.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{
char *pcBuffer = NULL;
/* Initial memory allocation */
pcBuffer = malloc(8);
//make sure piBuffer is valid or not
if (pcBuffer == NULL)
{
// allocation failed, exit from the program
fprintf(stderr, "Out of memory!\n");
exit(1);
}
strcpy(pcBuffer, "aticle");
printf("pcBuffer = %s\n", pcBuffer);
/* Reallocating memory */
pcBuffer = realloc(pcBuffer, 15);
if (pcBuffer == NULL)
{
// allocation failed, exit from the program
fprintf(stderr, "Out of memory!\n");
exit(1);
}
strcat(pcBuffer, "world");
printf("pcBuffer = %s\n", pcBuffer);
//free the allocated memory
free(pcBuffer);
return 0;
}
Output: pcBuffer = aticle pcBuffer = aticleworld
Note: It should be used for dynamically allocated memory but if a pointer is a null pointer, realloc behaves like the malloc function.
Answer:
he realloc function is used to resize the allocated block of memory. It takes two arguments first one is a pointer to previously allocated memory and the second one is the newly requested size.
The calloc function first deallocates the old object and allocates again with the newly specified size. If the new size is lesser to 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 exceeded size will be indeterminate.
Syntax:
Let’s see an example to understand the working of realloc in C language.
Output:
pcBuffer = aticle
pcBuffer = aticleworld
Note: It should be used for dynamically allocated memory but if a pointer is a null pointer, realloc behaves like the malloc function.
need an explanation for this answer? contact us directly to get an explanation for this answer