Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

pointers

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

like image 664
Kam Avatar asked Jan 17 '23 01:01

Kam


2 Answers

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.

like image 77
Alok Save Avatar answered Jan 20 '23 13:01

Alok Save


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-=2;

like image 24
tartar Avatar answered Jan 20 '23 13:01

tartar