Legal to overwrite std::string's null terminator?

后端 未结 4 421
感动是毒
感动是毒 2020-12-01 09:11

In C++11, we know that std::string is guaranteed to be both contiguous and null-terminated (or more pedantically, terminated by charT(), which in t

4条回答
  •  旧巷少年郎
    2020-12-01 09:50

    According to the spec, overwriting the terminating NUL should be undefined behavior. So, the right thing to do would be to allocate length+1 characters in the string, pass the string buffer to the C API, and then resize() back to length:

    // "+ 1" to make room for the terminating NUL for the C API
    std::string str(length + 1);
    
    // Call the C API passing &str[0] to safely write to the string buffer
    ...
    
    // Resize back to length
    str.resize(length);
    

    (FWIW, I tried the "overwriting NUL" approach on MSVC10, and it works fine.)

提交回复
热议问题