C++指针"错误:双重释放或损坏(退出)"

Kam*_*Kam 2 c++ pointers

这是我的代码:

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

}
delete[] ptemparr;
Run Code Online (Sandbox Code Playgroud)

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

double free or corruption (out)
Run Code Online (Sandbox Code Playgroud)

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

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

}
Run Code Online (Sandbox Code Playgroud)

这样我就可以在堆栈上创建指针,并且没有内存泄漏问题.此外,上面的代码必须每1秒运行一次,所以在让我知道这种情况的最佳编码实践之前,请记住这一点.

Alo*_*ave 5

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