What was the point of the GMEM_SHARE flag?

The GlobalAlloc function has a GMEM_SHARE flag. What was it for?

In 16-bit Windows, the GMEM_SHARE flag controlled whether the memory should outlive the process that allocated it. By default, all memory allocated by a process was automatically freed when that process exited.

Passing the GMEM_SHARE flag suppressed this automatic cleanup. That's why you had to use this flag when allocating memory to be placed on the clipboard or when you transfer it via OLE to another process. Since the clipboard exists after your program exits, any data you put on the clipboard needs to outlive the program. If you neglected to set this flag, then once your program exited, the memory that you put on the clipboard would be cleaned up, resulting in a crash the next time someone tried to read that data from the clipboard.

(The GMEM_SHARE flag also controlled whether the memory could be freed by a process other than the one that allocated it. This makes sense given the above semantics.)

Note that the cleanup rule applies to global memory allocated by DLLs on behalf of a process. Authors of DLLs had to be careful to keep track of whether any particular memory allocation was specific to a process (and should be freed when the process exited) or whether it was something the DLL was planning on sharing across processes for its own internal bookkeeping (in which case it shouldn't be freed). Failure to be mindful of this distinction led to bugs like this one.

Thank goodness this is all gone in Win32.

Comments (4)
  1. Matt C. Wilson says:

    "For information on obtaining this Service Pack, query on the following word in the Microsoft Knowledge Base (without the spaces):

    S E R V P A C K"

    What’s that all about?

  2. Mike Dunn says:

    I see many examples of putting data on the clipboard that use the GMEM_SHARED, GMEM_DDESHARE, or GMEM_MOVEABLE flags with GlobalAlloc. Are any of those necessary anymore?


  3. S E R V P A C K says:

    The spaces are there so that the word will not be index by search engines on that page.

  4. Raymond Chen says:

    As noted in the documentation for SetClipboarData, GMEM_MOVEABLE is required. More on this subject later.

Comments are closed.