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.
free is correct. Quoting from cppreference, description of constructor 3 (emphasis mine):
Constructs a view of the first count characters of the character array starting with the element pointed by s. s can contain null characters. The behavior is undefined if [s, s + count) is not a valid range (even though the constructor may not access any of the elements of this range). After construction,
data()is equal tos, andsize()is equal tocount.
So yes, you can safely pass result of data() call back to free().
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