3

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.

10
  • 1
    The pointer passed to free() must be equal to the value returned from malloc(). In practice sview.data() will be just that. But I'm ont sure it is guaranteed. Commented Jul 9 at 9:16
  • 3
    But why do you need to do something like that anyway ? And why not use std::string for the actual string ? Commented Jul 9 at 9:18
  • 2
    The whole purpose of a view is to be just... well... a view. It is, by definition, non-owning. So what you are trying to achieve, whether or not it is valid, defeats the purpose of using a view. Commented Jul 9 at 9:21
  • 2
    std::basic_string has possibility to use custom allocator. Else you can still have your own my_string, and use std::string_view for non-owning accesses. Commented Jul 9 at 9:42
  • 1
    @Njrslv-yndx-cloud "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" - you can use std::unique_ptr with a custom deleter to own and free the data. Let the string_view be just a view into the data, nothing more. Commented Jul 10 at 0:53

2 Answers 2

3

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().

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

Comments

2

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, <...>

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.