c++mallocc-stringsfreestring-view

Is it safe to call free on std::string_view::data?


Is it safe to call free in the example below:

size_t len = 10;
char* buffer = static_cast<char*>(malloc(len));
std::string_view sview(buffer, len);
free(sview.data())

Why do I need this? I have a mix of C++ and C code. I am using custom malloc and free. I want to use std::string_view instead of char* for the sake of STL containers, but I am also responsible for freeing the data.


Solution

  • Yes, it's safe although the aim is unclear. std::basic_string_view<CharT,Traits>::basic_string_view:

    constexpr basic_string_view( const CharT* s, size_type count ); (3)

    1. <...> After construction, data() is equal to s, <...>