Reputation: 2351
So this code of mine had the following realloc
block:
char **ptr = NULL;
void realloc_ptr(unsigned int new_size)
{
void *temp = NULL;
temp = realloc(ptr, new_size * sizeof(*ptr));
if(temp != NULL) {
ptr = temp;
}
else {
exit(EXIT_FAILURE);
}
}
new_size
is incremented right before this function is called. This array is always only expanded. Also, new_size
never exceeds 3 in my code (for now).
Now the above realloc
call worked fine during my testing in Windows 7. When I tested this code in XP, the above code would succeed 3 times and then it would throw an exception on the 4th time. I'll post the exact exception when I get back to the code (this computer doesn't have the code).
I'm guessing that my memory is too fragmented and the system could not allocate a contiguous block of memory. I have tested my code for memory leaks and fixed all of them (I hope). Any ideas why this is happening?
EDIT:
This above problem went away when I used Doug Lea's malloc.c. But I still want to know why this happened.
Thanks!
Upvotes: 2
Views: 333
Reputation: 62106
When I tested this code in XP, the above code would succeed 3 times and then it would throw an exception on the 4th time. I'll post the exact exception when I get back to the code (this computer doesn't have the code).
That (the exception) means you either have invalid pointers (or indices) somewhere (perhaps, uninitialized) and/or a memory corruption. realloc()
must fail silently and return NULL if the request cannot be satisfied.
And it's perfectly normal to have different behavior on different OSes.
Upvotes: 2
Reputation: 23560
My best guess is that new_size
is just too large to be available in contiguous virtual memory. You can never ever be sure that a large amount of contiguous virtual memory is available on 32-bit systems.
You generally should try to use multiple smaller blocks and if possible not even alloc them all at the same time but alloc'ing the next after the previous was free'ed.
Upvotes: 2