多次调用 realloc() 似乎会导致堆损坏
这段代码有什么问题?每次都会崩溃。
有时它是一个失败的断言“_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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你正在破坏堆。
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 yourptr
. Setptr
after reallocating.在循环的第二次迭代中,值
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 sizesizeof(buf)
size
has a value ofsizeof(buf)
Given these values the value of
ptr
is that it points past the end of the buffer allocated intodata
. This is memory not owned by the process and the followingmemcpy
operation writes to this and corrupts memory.此处对 realloc() 的调用可能会在返回新缓冲区之前释放旧缓冲区。
The call to
realloc()
here can potentially free the old buffer, before returning the new one.