Firstly, the assignment from a string literal to a char*
variable does not copy the string data into the memory you allocated. Instead it simply reassigns the pointer so that var
no longer points at the memory you allocated. That means the memory you allocated is lost and never properly deallocated, and it means that you're using delete
with a pointer that you never allocated, which is invalid.
Secondly, you're allocating an array with new char[]
, so you need to use delete []
instead of just delete
.
Thirdly, String literals automatically include a null terminator, so you don't need to add an extra one:
var = "hola mundo";
Lastly, if you can use C++11 or C++14 you should not be using new
and delete
directly. In earlier versions of C++ you can still avoid new
and delete
in many cases. In this case, since there's already a std::string
type you should simply use that no matter what version of C++ you're using. Your three lines of code should be replaced with:
std::string var = "hola mundo";
This is simpler and safer.