Reputation: 629
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?
Upvotes: 4
Views: 378
Reputation: 46027
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.
Upvotes: 5
Reputation: 161
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.
Upvotes: 5
Reputation: 1021
yes, its fine, cause you copy chars from buffer to data, so there is no link between two variables after copy is completed. Also you should consider more effective option to copy char* to string, for example this one http://www.cplusplus.com/reference/string/string/operator+=/
Upvotes: 3
Reputation: 38267
You can see from the signature of std::string::push_back
void push_back( CharT ch );
that the function argument is copied. Hence, deleting any resource that owned the char
after it has been copied into some string is fine.
Note that you can also avoid the manual looping by
data.insert(data.end(), buffer, buffer + buffer_size);
Upvotes: 3
Reputation: 500
It's safe. But you may also use std::string::append(const char*s , size_t n);
Upvotes: 3