Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting Char* after assigning it to a String Variable [duplicate]

Tags:

c++

string

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 ..?

like image 695
Manikandaraj Srinivasan Avatar asked Jan 22 '26 16:01

Manikandaraj Srinivasan


2 Answers

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.

like image 197
masoud Avatar answered Jan 25 '26 06:01

masoud


Is deleting a char array after creating a std::string from it safe?

Yes

like image 34
Aniket Inge Avatar answered Jan 25 '26 06:01

Aniket Inge