I assume when I do char* = "string" its the same thing as char* = new char[6]. I believe these strings are created on the heap instead of the stack. So do I need to destroy them or free their memory when I'm done using them or do they get destroyed by themselves.
You don't know where the string literals are stored. It may even be read-only memory, so your code should read:
const char* c = "string";
And a new char array should be deleted just like any other dynamically allocated memory area.
They're not the same. Your first example is a constant string, so it's definitely not allocated from the heap. Your second example is a runtime memory allocation of 6 characters, and that comes from the stack. You don't want to delete your first example, but you need to delete [] your second example.
I assume when I do char* = "string" its the same thing as char* = new char[6].
No. What the first one does is create a constant. Modifying it is undefined behaviour. But to answer your question; no, you don't have to destroy them. And just a note, always use std::string
whenever possible.
No. You only need to manually free strings when you manually allocate the memory yourself using the "malloc" function (in C) or the "new" operator (in C++). If you do not use malloc or new, then the char* or string will be created on the stack or as a compile-time constant.
new is always an allocation whereas defining a string inline actually embeds the data in the program itself and cannot be changed (some compilers allow this by a smart trick, don't bother).
Some compilers type inline strings so that you cannot modify the buffer.
char* const sz1 = "string"; // embedded string, immutable buffer
char* sz2 = new char[10]; // allocated string, should be deleted
No. When you say:
const char* c = "Hello World!";
You are assigning c to a "pre-existing" string constant which is NOT the same as:
char* c = new char[6];
Only in the latter case are you allocating memory on the heap. So you'd call delete when you're done.
The name of the game is "destroy only what you created". Here are the pairs:
- malloc/free
- calloc/free
- new/delete
- new[]/delete[]
Since you created the 2nd string using new[], the onus is on you to destroy it with delete[]. Call delete [] string2
when you are done.
Now if your code is convoluted enough and makes keeping track of deletions difficult, consider the usage of scoped pointers or auto pointers. The scoped_ptr class from boost library boost::scoped_ptr is a good place to begin. Also look into the RAII idiom, pretty handy and useful stuff.