Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 231
Njrslv-yndx-cloud Avatar asked May 29 '26 05:05

Njrslv-yndx-cloud


1 Answers

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 to s, and size() is equal to count.

So yes, you can safely pass result of data() call back to free().

like image 195
Yksisarvinen Avatar answered May 31 '26 17:05

Yksisarvinen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!