Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

char* new and delete [] error when a string is assigned

I need a C++ refresher. Why does this gives a memory exception?

pear = new char[1024];
pear = "happy go lucky";
delete [] pear; // exception
like image 274
Jake Avatar asked Apr 26 '12 06:04

Jake


2 Answers

pear = new char[1024];

Memory for 1024 character is allocated from heap and pear points to the start of it.

pear = "happy go lucky";

pear now points to the string literal which resides in the read-only segment and the previously allocated memory is leaked.

delete [] pear;

You try to free the read-only string, which is a undefined behaviour manifested as a runtime exception.

like image 149
codaddict Avatar answered Nov 13 '22 22:11

codaddict


pear = "happy go lucky";

This replaces the pointer allocated by new char[]. So now your delete[] pear tries to free the statically allocated string.

That's bad. You can only delete what you allocate with new. And since you overwrote (and lost) that pointer, you can't delete it.

like image 37
Nicol Bolas Avatar answered Nov 14 '22 00:11

Nicol Bolas