const char* s1 = "John";
const char* s2 = new char[] {"Cena"};
// is s1 on stack?
// is s2 on heap?
...
// use s1 and s2
...
delete s1;
// do I need to delete s1?
delete[] s2?
// s2 definitely must be deleted right?
I have added my questions in the comments above. Thanks in advance.
You may delete what was created using the operator new.
String literals have static storage duration. They are alive until the program ends.
In this code snippet
const char* s1 = "John";
const char* s2 = new char[] {"Cena"};
there is allocated dynamically only the array initialized by the string literal "Cena"
. So to delete it (to free the allocated memory) you need apply the operator delete [] to the pointer s2
.
delete [] s2;