0

Let's say I have allocated a string using SysAllocString. A separate class which is using the string calls SysAddRefString. Before it releases the string with SysReleaseString, the original owner class is calling SysFreeString. Would this create a problem?

Ie. do these functions always have to be called in this specific order:

SysAllocString
SysAddRefString
SysReleaseString
SysFreeString

Or is this ok? I have tried and it seems to work, but I don't know if there can be any potential problems:

SysAllocString
SysAddRefString
SysFreeString (memory is not released)
SysReleaseString (memory is actually released here)
8
  • 1
    That's entirely the point of using SysAddRefString(). Not intentionally getting this wrong is of course the sane approach. Commented Dec 13, 2023 at 23:46
  • So what does SysFreeString do exactly? If I don't call it in step 3, the memory is not freed when I call SysReleaseString in the last step Commented Dec 14, 2023 at 8:14
  • 1
    SysAddRefString protects against a bug in code you cannot change. Code that calls SysFreeString when it should not. Basic rule is that the code that called SysAllocString must be the code that calls SysFreeString. That rule gets fumbled too often. SysAddRefString "pins" the string so a buggy SysFreeString can't cause a dangling pointer, a highly exploitable mishap. If you don't have to deal with this bug, or don't have to call code you don't trust, then there is no point in using it. This is the kind of thing that Microsoft worries about, it is their code that gets attacked. Commented Dec 14, 2023 at 9:17
  • In my code I have a class which owns the string (it calls Alloc and Free), and I have classes which share or "borrow" the same string data instead of copying (they use AddRef and Release). Sometimes when owner class goes out of scope first and is terminated, SysFreeString would be called first. Is this ok, or should I generally avoid AddRef/Release altogether? Commented Dec 14, 2023 at 10:56
  • 1
    Just wrap the string into its own object. Now everybody that wants a view can call AddRef, there is only a single copy of it, and it only gets destroyed when the last one calls Release. Commented Dec 14, 2023 at 12:44

0

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.