The first example does not work when you go to delete the pointer. The program either hangs when I add the null terminator or without it I get:
Debug Assertion Fai
There are 3 things to understand:
1) char *at;
is just a pointer variable.
A pointer variable simply means that it holds a memory address.
2) new char[3]
returns the starting address of the memory allocated on the heap.
3) "hello"
returns the address of the string literal.
char *at = new char [3];
//at now contains the address of the memory allocated on the heap
at = "hello";
//at now contains the address of the static string.
// (and by the way you just created a 3 byte memory leak)
delete[] at;
//WOOPS!!!! you can't do that because you aren't deleting
// the original 3 chars anymore which were allocated on the heap!
//Since at contains the string literal's memory address you're
// trying to delete the string literal.
A note about modifying read only memory:
Also you should never be modifying a string literal. I.e. this should never be done:
char *at = "hello";
at[2] = '\0';
The memory for string literals must be read only and if you change it, the results are undefined by the C++ language.
Since you're using C++:
Since you're using C++ please consider using the std::string
type instead.
#include
using namespace std;
int main(int argc, char **argv)
{
string s = "hello";
s += " world!";
//s now contains "hello world!"
s = "goodbye!";
//Everything is still valid, and s contains "goodbye!"
//No need to cleanup s.
return 0;
}