The string "hey"
has its space pre-allocated as part of the program, so it just appears when the program starts and disappears when the program ends.
If you want to see a program that allocates memory, uses it, then deletes it, then look at this:
#include <iostream>
using namespace std;
int main(int argc, char *argv[]){
const char *hey="hey";
char* tmp=new char[4]; // NB allocate 4 chars for "hey" plus a null terminator
strcpy(tmp,hey); // copies the string and null terminator
cout << tmp << endl;
delete [] tmp;
// must not use tmp now as it points to deallocated memory
// must not delete hey
return 0;
}
Notice how I happened to delete the new
'd memory using tmp
. I could have done this:
cout << tmp << endl;
hey = tmp;
delete [] hey;
It doesn't matter whether, in the end, we point to the new
'd memory with hey
or tmp
, just as long as we delete it properly to avoid memory leaks.