Hi all,
i'm questioning something about GlobalFree.....
every time i need some bytes (>8 ) of memory i call GlobalAlloc and save the fixed pointer in an undefined variable (dd ?). Since some of my own functions return the pointer to such allocated memory, I always "GlobalFree" those pointers in my main (calling) procedure after I used them, except the returned pointer is zero :)
So but when windows api functions return pointers to strings or structures in memory, why is there no need to "GlobalFree" those, too? are they released automatically or is the prog growing with those unused memory parts until it gets closed? I somewhere read that some returned pointers are just well for a short time, so the buffer can be examined or copied, but the program should never relate on that pointer some time after it was returned. In special cases I think it was. Or am I just a memory freak that does not need to GlobalFree his variables at all (except their size is really huge)!?!?!?
Please help
Posted on 2004-11-05 16:08:16 by Dom
First of all, the Global* memory functions are a holdover from the good old 16-bit Windows era and should only be used when needed (DDE, OLE, Clipboard).

Secondly, most of the Windows API that returns strings or structures require the program to allocate the memory and pass the API the pointer and Windows will use your allocated memory. This puts the burden of allocating and freeing on the programmer. There are a few APIs that return pointers where Windows has allocated the memory, and in those cases the documentation will state which function you should use to free it.
Posted on 2004-11-05 19:41:19 by Mecurius
If API requires/returns GlobalAlloc()'ed memory, that means the memory area is shared across processes. Unless it is documented that GlobalFree() is the caller's responsibility, do not free it. Otherwise, you may cause some strange crash in seemingly unreleated applications.

Even if that leads to mem leak, that is not your fault, but MS documentation team's. Although MS documentation track record is lousy, adventure into undocumented area is more troublesome.
Posted on 2004-11-06 00:52:27 by Starless
Which APIs are you worried about?

GetCommandLine returns a pointer to a string that is never changed or freed by Windows after your program starts running.

MFC string functions are special - there are rules to follow if you don't want memory leaks or dangling pointers.

The other nonMFC, nonCOM API functions I've used all require you to pass a pointer to a data area you allocate. They fill your data area with the information they provide.
Posted on 2004-11-06 02:40:54 by tenkey
If you want to allocate a small amount of memory (less then Kb) use HeapAlloc
Posted on 2004-11-06 05:41:34 by greenant