4

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?
1
  • No, that's perfectly fine. Commented Mar 18, 2019 at 9:39

5 Answers 5

5

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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.

Comments

3

It's safe. But you may also use std::string::append(const char*s , size_t n);

Comments

3

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);

Comments

3

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+=/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.