为什么在尝试在堆上释放内存时,我会收到错误:“双免费或损坏(OUT)核心倾倒中止的核心倾倒&quot”?
我已经使用了malloc 2-d阵列,它是:
charArray = (char **)malloc(rows * sizeof(char *));
for (i = 0; i < columns; i++)
charArray[i] = (char *)malloc(columns * sizeof(char *));
当我尝试释放内存时,它说:“双免费或腐败(out)。中止(核心倾倒)。这就是我的释放方式:
for (i = 0; i < rows; i++) {
free(charArray[i]);
charArray[i] = NULL;
}
free(charArray);
charArray = NULL;
为什么我要获取此错误,我该如何解决
? /I.sstatic.net/vxr2r.png“ alt =”在此处输入图像描述”>
I have used a malloc 2-D array and this it:
charArray = (char **)malloc(rows * sizeof(char *));
for (i = 0; i < columns; i++)
charArray[i] = (char *)malloc(columns * sizeof(char *));
And when I try to free the memory, it says: "double free or corruption(out). Aborted (core dumped). This is how i free it:
for (i = 0; i < rows; i++) {
free(charArray[i]);
charArray[i] = NULL;
}
free(charArray);
charArray = NULL;
Why do I get this error and how can I fix it? This is the valgrind report:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从您发布的代码中也很难看。
使您的生活更轻松,并使用阵列指针。
只需要一个分配和免费。间接级别较少 - 更快的代码。
From the code you posted it is hard too see.
Make your life easier and use array pointers.
Only one allocation and free is needed. Fewer levels of indirection - faster code.
至少可以说您的代码片段是简短的,但是分配循环中存在问题:
for(i = 0; i&lt; columns; i ++)
应该在cow> cow ,不是
列
并分配列
字符,而不是指针。如果
行
和列
不同,则您的行为不确定:列&gt;行
和分配代码在分配的块的末端以chararray
rows&gt;列
,您试图释放未分配并且可能无效的指针。为了避免这种错误,建议使用
sizeof
与目标元素类型:分配
char> char
的平面2D数组,而不是间接数组也更简单:此数组也更简单地释放:
Your code fragment is terse to say the least, but there is a problem in the allocation loop:
for (i = 0; i < columns; i++)
should iterate onrows
, notcolumns
and allocatecolumns
characters, not pointers.If
rows
andcolumns
differ, you have undefined behavior:columns > rows
and the allocation code writes pointers beyond the end of the allocated block forcharArray
rows > columns
and you attempt to free pointers that were not allocated and are probably invalid.To avoid such mistakes, it is recommended to use
sizeof
with type of the destination element:It would also be simpler to allocate a flat 2D array of
char
instead of an indirect array:This array is also simpler to free: