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

3

7

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

pear = new char[1024];
pear = "happy go lucky";
delete [] pear; // exception
Hodson answered 26/4, 2012 at 6:15 Comment(1)
is the first line equal to char* pear = new char[1024]; ?Edacity
D
9
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.

Drew answered 26/4, 2012 at 6:18 Comment(0)
S
5

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.

Singleminded answered 26/4, 2012 at 6:18 Comment(0)
P
2

What you're doing is assigning pear to an allocated array of chars on the heap, and then reassigning it to point to the string which is in a static location. If you try to delete that it will error because you're not supposed to delete stuff in that static location.

Pinkie answered 26/4, 2012 at 6:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.