I am trying to reallocate memory using realloc in the below program and checking after realloc initial memory which i was reacted using malloc(i = (int*)malloc(5 * sizeof(int))) still exist or not, using below program i am able to access the data after realoc i have checked by using another pointer (i.e *m). is this proper behavior ? or memory should be free once realloc called?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *i,*jn, *m;
i = (int*)malloc(5 * sizeof(int));
int j,k=10;
for(j=0 ;j<5; j++)
{
i[j] = j;
printf("%d \n",i[j]);
}
for(j=0 ;j<5; j++)
{
printf("%p\n",i++);
}
jn = (int *)calloc(5, sizeof(*i));
for(j=0 ;j<5; j++)
{
printf("%p\n",jn++);
}
i = i-5;
m = i;
printf("m = %p %d\n",(m+1), *(m+1));
i =(int *)realloc(i,8*sizeof(int));
for(j=0 ;j<8; j++)
{
printf("%d\n",i[j]);
}
for(j=0 ;j<8; j++)
{
printf("%p\n",i++);
}
printf("m = %p %d\n",(m+1), *(m+1));
return 0;
}
reallocsucceeds, it will take ownership of the incoming memory (either manipulating it orfreeing it) and return a pointer that can be used ("owned") by the calling function. Ifreallocfails (returnsNULL), your function retains ownership of the original memory and shouldfreeit when it's done with it.