Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking to see if a pointer can be freed

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.

like image 285
James Avatar asked Jan 01 '11 05:01

James


2 Answers

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

  • making the user of the library manage the memory himself, or
  • requiring the user to tell you how to manage the memory, or
  • telling the user how you are going to manage the memory and then expecting the user to comply.
like image 120
James McNellis Avatar answered Sep 29 '22 15:09

James McNellis


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.

like image 31
Ben Voigt Avatar answered Sep 29 '22 14:09

Ben Voigt