Hello, maybe that's a stupid question, but does the realloc function save the previous saved data into the reallocated buffer?
Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *bff,*tmp;
int l;
l=strlen("hello")+1;
if(!(bff=malloc(l))) {getch();return 0;}
memset(bff,0,l);
sprintf(bff,"hello");
l=strlen(bff)+strlen(" world")+1;
if((tmp=realloc(bff,l)))//here's my question
{
bff=tmp;
strcat(bff," world");
}
printf("%s",bff);
memset(bff,0,l);
free(bff);
getchar();
return 0;
}
Output:
hello world
I have tested that code (with dev-cpp / mingw) several times and it have worked, but I'm not sure if that works because that's a right coding practice or because somekind of coincidence have done it. I have tested some more and find that the pointer to a reallocated buffer after the reallocation have no data but it isn't a null pointer, but the data contents is still there in the memory, and tmp have the pointer to that memory:
Code:
//modification on the previous code
if((tmp=realloc(bff,l)))
{
printf("BFF=%s\nTMP=%s\n%s\n",bff,tmp,((!bff)?"NULL BFF":"NOT NULL BFF"));
bff=tmp;
strcat(bff," world");
}
Output:
BFF=
TMP=hello
NOT NULL BFF
So realloc quits the pointer from the bff and asign it to the tmp (no?), the data stored previously in that point is still in that point that now is accessible from tmp, because of that I have to 'bff=tmp' to re-set the pointer to the main buffer. That will ensure that the data previously saved there will still be there after a reallocation (in all the cases)? Or is not a safe method? Or there's some situation that can fail that?
Thank's in advance
Niara