Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are you allowed to copy a pointer and call delete on the copy?

If I copy a pointer and then ask for the pointed to allocation to be deleted, is it valid C++, or is it undefined behavior?

char* orig = new char[100];
char* copy = orig;
delete[] copy;
like image 763
Steve M Avatar asked Oct 21 '25 16:10

Steve M


1 Answers

It's perfectly valid. You are deallocating the array that you allocated on the first line.

Note that copying the pointer doesn't copy the allocated array. So you allocate one array and then you deallocate one array, leaving you with no arrays remaining.

like image 198
Joseph Mansfield Avatar answered Oct 23 '25 12:10

Joseph Mansfield



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!