Hello everybody,
Can anyone suggest why delete is not working in the following code :
Code:char *str = new char[12]; str = "Hello World"; cout <<"\n\n The string is : "<< str; //delete str;
Hello everybody,
Can anyone suggest why delete is not working in the following code :
Code:char *str = new char[12]; str = "Hello World"; cout <<"\n\n The string is : "<< str; //delete str;
Aslaville is right to say that you should match new char[12] with delete[]. However, there's another mistake:
Since you assign a pointer to the first element of the string literal to str, you can no longer use delete[] on str. In fact, you have a memory leak since you now have no way to call delete[] on the memory allocated in the previous line.Code:str = "Hello World";
There are a few ways to solve this, but I suggest simply using std::string:
Code:std::string str = "Hello World"; cout << "\n\n The string is : " << str;
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
@laserlight, please suggest other methods that you know.
You could use some form of copying if you want to explicitly use new(). Or you need t o assign the value for each character manually.
This link might help : c - Why can a string be assigned to a char* pointer, but not to a char[] array? - Stack Overflow
It seemed kind of relevant to your usage.