multiple calls to realloc() seems to cause a heap corruption..

Posted by Windindeed on Stack Overflow See other posts from Stack Overflow or by Windindeed
Published on 2010-06-07T20:56:17Z Indexed on 2010/06/07 21:02 UTC
Read the original article Hit count: 162

Filed under:
|
|

What's the problem with this code? It crashes every time.

One time it's a failed assertion "_ASSERTE(_CrtIsValidHeapPointer(pUserData));", other times it is just a "heap corrpuption" error.

Changing the buffer size affects this issue in some strange ways - sometimes it crashes on the "realloc", and other times on the "free".

I have debugged this code many times, and there is nothing abnormal regarding the pointers.

char buf[2000];
char *data = (char*)malloc(sizeof(buf));
unsigned int size = sizeof(buf);

for (unsigned int i = 0; i < 5; ++i)
{
    char *ptr = data + size;
    size += sizeof(buf);
    char *tmp = (char*)realloc(data, size);
    if (!tmp)
    {
        std::cout << "Oh no..";
        break;
    }
    data = tmp;
    memcpy(ptr, buf, sizeof(buf));
}

free(data);

Thanks!

© Stack Overflow or respective owner

Related posts about c++

Related posts about realloc