C++ 指针“错误:双重释放或损坏(输出)”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9901339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:23:00  来源:igfitidea点击:

C++ pointer "error: double free or corruption (out)"

c++pointers

提问by Kam

This is my code:

这是我的代码:

uint16_t * ptemparr = new uint16_t[20];
for (int x=0;x<2;x++)
{
   function(ptemparr);
   ptemparr ++;

}
delete[] ptemparr;

When I do that I get this error:

当我这样做时,我收到此错误:

double free or corruption (out)

EDITED: Thank you I understood why I get this error, now do you think this is a better idea?

编辑:谢谢我明白为什么我会收到这个错误,现在你认为这是一个更好的主意吗?

uint16_t temparr[20];
uint16_t * ptemparr = temparr;
for (int x=0;x<2;x++)
{
   function(ptemparr);
   ptemparr ++;

}

This way I make the pointer on the stack and there's no memory leak issue. Also, this code above has to run every 1 sec, so please bare this in mind before letting me know what's the best coding practice for this situation

通过这种方式,我将指针放在堆栈上,并且没有内存泄漏问题。此外,上面的代码必须每 1 秒运行一次,所以在让我知道这种情况的最佳编码实践是什么之前请记住这一点

回答by Alok Save

You need to pass the same address to delete []which was returned by new [].
Also, make sure function()does notdeallocate the memory by callingdelete`on the passed pointer.

您需要传递由delete []返回的相同地址new []
另外,请确保function()不要deallocate the memory by calling删除传递的指针。

回答by tartar

you need to reset ptemparr to its home address since you incremented it in your for loop. so, I suggest decrementing it by 2 before deleting it.

您需要将 ptemparr 重置为其家庭地址,因为您在 for 循环中增加了它。所以,我建议在删除它之前将其减少 2。

ptemparr-=2;

ptemparr-=2;

回答by Jonathon Reinhart

You need to deletethe same address returned by new.

您需要delete返回相同的地址new

I always make my loops line this work on a copy of the original pointer, and never modify the original pointer returned by mallocor new.

我总是让我的循环在原始指针的副本上工作,并且从不修改由mallocor返回的原始指针new