-
realloc
Hi guys,
I've been using the realloc() function for a while, and I think the function can sometime cause a memory leak if not used well.
Here is the code:
Code:
int main(void)
{
long *pArray, *pTemp;
int i;
pArray=malloc(sizeof(*pArray)*5);
if (pArray==NULL)
{
puts("Failed to allocate memory!");
exit(1);
}
pTemp=realloc(pArray,sizeof(*pTemp)*1000);
if (pTemp==NULL)
{
puts("Failed");
exit(1);
}
for (i=0;i<10;++i)
pTemp[i]=i;
// ****************************************
// This is the new code line I've never used before!
// ****************************************
if (pTemp==pArray)
{
pArray=pTemp;
puts("Same address!");
}
else
{
free(pArray);
pArray=pTemp;
puts("Diffetent Address");
}
free(pTemp);
return 0;
}
For some reason I never saw this implemention anywhere in my books or on the net.
Because realloc priority is to reallocate memory in the preview allocation address (to skip copying the old values), this not always the case, so assigning the new allocation address (pTemp) to the old one (pArray) will cause a memory leak.
Am I right?
-
No, that's not correct. By definition realloc() will deallocate the old memory (unless it can't allocate enough new storage). What that means is that you absolutely should not free pArray the way you are in your example. It will have already been deallocated by realloc(). Your code is overly complex. You should use realloc() something like this:
Code:
#include <stdlib.h>
#include <assert.h>
int main(void)
{
void *p, *t;
p = malloc(50);
assert(p != NULL);
t = realloc(p, 5000);
if(t == NULL)
{
/* deal with insufficient memory condition.
* note that p is still valid at this point.
*/
}
else
{
/* allocation was successful, reassign p */
p = t;
}
/* do something with p */
free(p);
return 0;
}