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 ..?
When you assign a C-style string (array of char) to a std::string. The overloaded assignment copies that C-style string to std::string.
std::string newStr = newCharP;
After this assignment, all characters of newCharP copy to newStr. Then you can delete newCharP safely.
Is deleting a char array after creating a std::string from it safe?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With