PDA

View Full Version : realloc() memory leaks.


Skorche
2006.09.04, 03:20 PM
I'm having a bit of trouble with my infinite arrays. According to MallocDebug the problem is the call to realloc() in the code below.

void
cpArrayPush(cpArray *cparr, void *object)
{
cparr->arr[cparr->num] = object;

cparr->num++;
if(cparr->num == cparr->max){
cparr->max += CP_ARRAY_INCREMENT;
cparr->arr = realloc(cparr->arr, cparr->max*sizeof(void**));
}
}

realloc() is supposed to free the old pointer isn't it?

akb825
2006.09.04, 03:22 PM
realloc is actually supposed to add to the current pointer, if possible. If not, it's supposed to create a new pointer and free the old.

The realloc() function tries to change the size of the allocation pointed
to by ptr to size, and return ptr. If there is not enough room to
enlarge the memory allocation pointed to by ptr, realloc() creates a new
allocation, copies as much of the old data pointed to by ptr as will fit
to the new allocation, frees the old allocation, and returns a pointer to
the allocated memory. realloc() returns a NULL pointer if there is an
error, and the allocation pointed to by ptr is still valid.
The only time it doesn't free the memory is if there isn't a block large enough for realloc to allocate, and it fails. (it keeps the old pointer, but since you've already set the old pointer to the return value, it's lost)

Skorche
2006.09.04, 03:30 PM
The only time it doesn't free the memory is if there isn't a block large enough for realloc to allocate, and it fails. (it keeps the old pointer, but since you've already set the old pointer to the return value, it's lost)

Yeah, I know that I should be catching the error condition, but that can't be what's causing the problem or I'd be getting bus errors right?

Skorche
2006.09.04, 04:23 PM
And fixed. In my spatial hash, I was freeing the objects in a certain cpArray, but never the cpArray itself.

OneSadCookie
2006.09.04, 08:01 PM
There is a nonstandard function called reallocf that will free the existing array if the realloc fails. That means that x = reallocf(x, s) (may be) safe, if not helpful ^_^

Skorche
2006.09.04, 08:25 PM
There is a nonstandard function called reallocf that will free the existing array if the realloc fails. That means that x = reallocf(x, s) (may be) safe, if not helpful ^_^

Yeah, I saw that in the man page for realloc().

Why would you want it to automatically throw the array away? If you use realloc() the right way and check for NULL, you could possibly recover from the error by freeing up other memory.