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