Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add char to a String and delete the char array

Tags:

c++

Is adding a char from a char* to a std::string and then delete[] the char array can cause UB?

or is it safe to process the string after the delete[] ?

int buffer_size = 4096;
char* buffer = new char[buffer_size];

//here there was removed code that assign values to the buffer[i]    

std::string data;

for (int i = 0; i < buffer_size ; i++)
{
    data.push_back(buffer[i]);
}

delete[] buffer;

//is the data string content secured at this point?
like image 374
dvrer Avatar asked Dec 02 '22 09:12

dvrer


2 Answers

The definition of the push_back function is

void push_back( CharT ch );    

As the parameter ch is passed by value and not by reference, it is copied into the string, therefore deleting the source of the char you appended to the string does not cause any issues.

like image 129
Lukas Schulte Avatar answered Dec 04 '22 02:12

Lukas Schulte


Deleting after creating the string is fine as push_back copies the data. However, a better method is to use simply:

std::string data(buffer, buffer_size);

Calling push_back in a loop may trigger memory allocation multiple times. But with the constructor whole buffer_size memory is allocated at once.

like image 37
taskinoor Avatar answered Dec 04 '22 02:12

taskinoor