The realloc() function is defined in the stdlib.h header file. It helps to resize the memory block pointed by the pointer which is previously allocated using the malloc() or calloc() function.
void *realloc(void *ptr, size_t size); #where size should be a bytes
The realloc() function takes two parameters. If ptr is is NULL, a new block is allocated and a pointer to it is returned.
Parameter | Description | Required / Optional |
---|---|---|
ptr | pointer to a memory block previously allocated and need to be reallocated | Required |
size | the new size for the memory block, in bytes | Required |
If size is 0 and ptr points to an existing memory block, the memory block pointed by ptr is deallocated and a NULL pointer is returned.
Input | Return Value |
---|---|
success | pointer to memory |
fails | NULL |
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *s;
/*memory allocation */
s = (char *) malloc(12);
strcpy(s, "programming");
printf("String = %s, Address = %u\n", s, s);
/* Reallocating memory */
s = (char *) realloc(s, 20);
strcat(s, ".com");
printf("String = %s, Address = %u\n", s, s);
free(s);
return(0);
}
Output:
String = programming, Address = 355090448 String = programming.com, Address = 355090448
#include <stdio.h>
#include <stdlib.h>
int main (){
int k, * p, t = 0;
p = malloc(200);
if (p == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
p = realloc(p,400);
if(p != NULL)
printf("Memory created successfully\n");
return 0;
}
Output:
Memory created successfully