I've looked all over for an answer to this but can't seem to find one. (I have fairly limited experience with C++)
In my library, I free a string. (Amazing, huh?)
This is where the problem arises. I have a struct which contains a char* that may be allocated on the heap or may not be. While it is a valid pointer it cannot be freed.
IE
char* s1 = "A String";
char* s2 = (char*)memcpy(malloc(9), s1, 9);
free(s2);
free(s1);
Will cause an error on "free(s1);" (As it should) Because s1 does not actually need to be freed, (It isn't on the heap) how can I handle this in an "acceptable" way? (On similar topics the answer of "let it crash" didn't seem reasonable IMO)
Because the struct is not solely created by the library, it is not possible to guarantee that a string will be properly copied over using something like memcpy.
Seeing as this is a windows library, I don't need to worry about using ISO C stuff or standard C functions.
In C++, you shouldn't be worrying about this at all. Use std::string
and have it manage memory for you, automatically. Don't manage memory manually.
If you were to do this manually, you would need to manage the resource yourself, by
Seeing as this is a Windows library, make the argument a BSTR
. Then you require the user to allocate it properly (with SysAllocString
) and you're guaranteed to use a matching deallocator.
Other methods are just... bad. If your user has a different compiler, then you can't free()
the string even if they did use malloc
.
[Note: Converted from a comment at James's request, this really is just a Windows-specific case of the last of his suggestions]
Further note: BSTR is Unicode. I kinda sorta remember seeing a way to use the BSTR allocator to store ANSI strings, seems that SysAllocStringByteLen
does that, but be warned that putting ANSI data in a BSTR will be highly counterintuitive to anyone familiar with BSTR.
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