1

这段代码有什么问题?每次都会崩溃。

有时它是一个失败的断言“_ASSERTE(_CrtIsValidHeapPointer(pUserData));”,有时它只是一个“堆损坏”错误。

更改缓冲区大小会以一些奇怪的方式影响这个问题 - 有时它会在“realloc”上崩溃,而其他时候会在“free”上崩溃。

这段代码我调试过很多次,指针没有任何异常。

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);

谢谢!

4

3 回答 3

1

你正在破坏堆。realloc可以自由选择在重新分配时从完全不同的位置返回内存,这会使您的ptr. 重新分配后设置ptr

于 2010-06-07T21:00:25.253 回答
0

在循环的第二次迭代中,这里是值

  • data指向一个大小的缓冲区sizeof(buf)
  • size has a value of sizeof(buf)

Given these values the value of ptr is that it points past the end of the buffer allocated into data. This is memory not owned by the process and the following memcpy operation writes to this and corrupts memory.

于 2010-06-07T21:00:25.940 回答
0
char *ptr = data + size;
char *tmp = (char*)realloc(data, size);
memcpy(ptr, buf, sizeof(buf));

The call to realloc() here can potentially free the old buffer, before returning the new one.

于 2010-06-07T21:01:41.087 回答