views:

86

answers:

2

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;
}
A: 

run it under valgrind or electric fence - these will spot memory overruns for you

pm100
+2  A: 

class->name = name isn't doing what you think it is. Use strncpy() 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 call setName(), you end up calling realloc() with a pointer that you didn't get from malloc(). I expect somewhere that you're calling setName() with a constant, global variable, or local variable string, and that's what eventually generates the error. If you were only ever calling setName() with strings whose memory you got from malloc(), you wouldn't see the warning from gdb (but you'd still have the bug!).

Carl Norum
+1 for nailing it !
Paul R
And given that you're always overwriting what was stored in the allocated buffer, there's no need to use `realloc` at all - just `free` and `malloc` will be fine.
caf