Author Topic: Warning! Don't store the result of wxString::mb_str() in a char*.  (Read 5220 times)

Offline me22

  • Official tester
  • Multiple posting newcomer
  • ***
  • Posts: 53
    • TA Universe
Don't write code like
Code: [Select]
char const * psz = str.mb_str(wxConvUTF8);wxString::mb_str() returns a buffer, not a raw pointer.  This is a good thing because the buffer's destructor takes care of freeing the memory used by the string.  This buffer is implicitly convertible to a char const* so that it can be used in things like strlen( str.mb_str() ) immediatly, but that opens up the error I'm warning about in this post.

What actually happens in the above code?  wxString::mb_str() returns a buffer object.  Said buffer's implicit conversion to char const* is activated, and the result is stored in psz.  The temporary buffer then GOES OUT OF SCOPE and ITS DESTRUCTOR DELETES THE MEMORY.  It seems that windows doesn't care, but that linux often has already reused the memory by the time psz is used again in the code.

Code: [Select]
wxWX2MBbuf psz = str.mb_str(wxConvUTF8);wxWX2MBbuf takes ownership of the buffer ( no, it's not copied -- it's transfer of ownership semantics similar to std::auto_ptr ).  That way you can actually use the memory until psz goes out of scope and deletes it.