delete char*

Hello, I faced a problem

I declared a char* variable in a way like this:

char* chText = "Hello!";

And I need to free memory, taken by this variable.
If I use
delete chText;
or
delete[] chText;
Visual Studio reports, that "HEAP DESTRUCTION DETECTED".
But I need to free this memory, as it is a class' member, and I think that it can cause a memory leak when object will be destroyed. Or it will not cause leak?
That memory is not memory allocated by you, so you must not attempt to free it. It is not causing a memory leak.

FYI, the memory pointed to by the chText pointer is allocated by the compiler and the compiler will make sure it is freed.
char* chText = "Hello!"; is invalid current C++ (accepted as deprecated by older revisions of the C++ standard). The proper form is const char* chText = "Hello!";

You do not (and in fact cannot) free the memory occupied by the string literal "Hello!". A string literal is a static object. Static objects are allocated at program startup and deallocated at termination.

As a guideline, you can only delete what you have new'd.
Last edited on
http://www.cplusplus.com/reference/std/new/operator%20delete%5B%5D/

I think you only delete when you create a variable when using new.
I could be wrong though.
That memory is not memory allocated by you, so you must not attempt to free it. It is not causing a memory leak.

FYI, the memory pointed to by the chText pointer is allocated by the compiler and the compiler will make sure it is freed.

Thanks. I thought about it, but I just wanted to check
Topic archived. No new replies allowed.