多次调用 realloc() 似乎会导致堆损坏

发布于 2024-09-04 10:12:16 字数 581 浏览 8 评论 0原文

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

有时它是一个失败的断言“_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);

谢谢!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

孤单情人 2024-09-11 10:12:16

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

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.

夜灵血窟げ 2024-09-11 10:12:16

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

  • data 指向大小为 sizeof(buf) 的缓冲区
  • size 的值为 >sizeof(buf)

给定这些值,ptr 的值是它指向分配给 data 的缓冲区末尾。这是不属于进程的内存,以下 memcpy 操作会写入该内存并损坏内存。

On the second iteration of the loop here are the values

  • data points to a buffer of size 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.

遇见了你 2024-09-11 10:12:16
char *ptr = data + size;
char *tmp = (char*)realloc(data, size);
memcpy(ptr, buf, sizeof(buf));

此处对 realloc() 的调用可能会在返回新缓冲区之前释放旧缓冲区。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文