I have a simple C program which has a pointer to a character array. To initiate it, I use malloc, and resize then set it x number of times later on in the program.
When I resize it once with realloc, gdb doesn’t show any errors, however, if I try calling the resize function again, gdb shows the following error:
warning: Invalid Address specified to RtlReAllocateHeap( 003E0000, 00404076 )
Any ideas why resizing it more than once gives this error?
EDIT
I played around with it and it seems the error doesn’t happen when I comment out the setting of the pointer data, which is after the resizing.
void setName(struct class_x *class, char *name)
{
class->name = (char *) reallocateMemory(class->name, sizeof(char) * strlen(name) + 1);
class->name = name;
}
void *reallocateMemory(void *member, size_t size)
{
void *tmp = realloc(member, size);
if(tmp == NULL)
{
//handle
}
return tmp;
}
class->name = nameisn’t doing what you think it is. Usestrncpy()to copy the input string into your newly allocated memory. That assignment you have there is leaking your allocated memory and overwriting the pointer. Then the next time you callsetName(), you end up callingrealloc()with a pointer that you didn’t get frommalloc(). I expect somewhere that you’re callingsetName()with a constant, global variable, or local variable string, and that’s what eventually generates the error. If you were only ever callingsetName()with strings whose memory you got frommalloc(), you wouldn’t see the warning from gdb (but you’d still have the bug!).