ppescher / resizablelib

A set of MFC classes to easily make resizable windows
Other
55 stars 27 forks source link

Replace init_seg(lib) with a static initializer #7

Closed irwir closed 6 years ago

irwir commented 6 years ago

CRT heap debugger was reporting an unreleased block on program exit. It could have been a false positive, but replacing an object with a pointer would exclude construction/destruction code, because the static pointer would be initialized at compile time.

ppescher commented 6 years ago

Thanks irwir, I was aware of the apparent memory leak but never thought it could have been the static initializer (or maybe I forgot about its presence). Not really sure why I chose to use a CString there, I guess because I wanted to avoid problems with buffers ownership, such as when you assign a CString to an LPCTSTR. Also not sure why the #pragma's were necessary.

irwir commented 6 years ago

After investigating a similar issue with static objects, I am reasonably sure that this leak was a false positive. The reasons could be the following. By definition, static objects should be created when a program starts, and deleted on exit. According to #pragma, this CStringobject was getting memory allocation very early, before any user code and main() routine. Therefore, it shoud be destroyed after all user code in CRT program completion code which is inside exit(). It seems that heap debugger checks memory state before that destruction.

Finding what was in the unreleased memory block was not hard, but also not exactly trivial. So would be tracing the destruction of that static CStringobject. It was educating, but certainly most users would prefer to avoid that kind of exercises.

Therefore replacing the object with a pointer seems reasonable: no more false positives, and smaller code size. The rest of the related code uses only pointers, not CStrings, so it should be fine.

Also not sure why the #pragma's were necessary.

That kind of pragma is used to avoid issues with undefined initialization order.