Search code examples
c++reallocheap-corruption

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


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!


Solution

  • You're trashing the heap. realloc can freely choose to return you memory from an entirely different location as it reallocates, and this is invalidating your ptr. Set ptr after reallocating.