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

c++, delete-operator, memory, new-operator, runtime-error

Solution

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.

Problem

I need a C++ refresher. Why does this gives a memory exception? ``` pear = new char[1024]; pear = "happy go lucky"; delete [] pear; // exception ```

Original source