Deleting char* after assigning it to a string variable

c++, char, pointers, string

Solution

There is no problem, as long as `newChar` points to a null-terminated string, and is not null itself.

`std::string` has constructor that allows an implicit construction from a `const char*`. It makes a copy of the character string represented by the input `const char *` so it works under the assumption that the `char*` is a null terminated string, since there is no other way to know how many characters to copy into the string's own data storage. Furthermore, a `NULL` pointer is actually disallowed by the standard.

Problem

I have executed the below code and it works perfectly. Since it is about pointers, I just want to be sure. Though I'm sure that assigning char* to string makes a copy and even if I delete char*, string var is gonna keep the value. ``` #include <stdio.h> #include <string.h> #include <string> #include <iostream> int main() { std::string testStr = "whats up ..."; int strlen = testStr.length(); char* newCharP = new char[strlen+1]; memset(newCharP,'\0',strlen+1); memcpy(newCharP,testStr.c_str(),strlen); std::cout << " :11111111 : " << newCharP << "\n"; std::string newStr = newCharP ; std::cout << " 2222222 : " << newStr << "\n"; delete[] newCharP; newCharP = NULL; std::cout << " 3333333 : " << newStr << "\n"; } ``` I'm just changing some code in my company project and char* are passed between functions in C++. The char* pointer has been copied to the string, but the char* is deleted in the end of the function. I couldn't find any specific reason for this. So I'm just deleting the char*, as soon as it is copied into a string. Would this make any problem ...? P.S : I have already asked this question in Codereview , but I got suggestion to move it to SO. So i have flagged it for close there and posting the question here.

Original source