home *** CD-ROM | disk | FTP | other *** search
/ Microsoft Programmer's Library 1.3 / Microsoft-Programers-Library-v1.3.iso / sampcode / win_lrn / memory / global / globfree.c < prev    next >
Encoding:
C/C++ Source or Header  |  1988-08-11  |  2.1 KB  |  64 lines

  1. /*
  2.  *   This program demonstrates the use of the GlobalFree function. The
  3.  *   GlobalFree function frees memory allocated from the Global heap.
  4.  *   GlobalFree returns NULL if the memory is free. GlobalFree was called
  5.  *   from WinMain in this sample application.
  6.  *
  7.  */
  8.  
  9. #include "windows.h"
  10.  
  11. int sprintf();
  12.  
  13. typedef struct {     /* structure we are going */
  14.       int x;         /* to allocate and lock   */
  15.       int y;
  16.         } MYSTRUCT;
  17.  
  18. typedef MYSTRUCT far *lpMyPtr;    /* far pointer to MYSTRUCT type */
  19.  
  20. int PASCAL WinMain(hInstance, hPrevInstance, lpszCmdLine, cmdShow)
  21. HANDLE hInstance, hPrevInstance;
  22. LPSTR lpszCmdLine;
  23. int cmdShow;
  24. {
  25.     HANDLE hMemBlock;   /* Handle to memory block       */
  26.     lpMyPtr  ThisPtr;   /* Pointer to myStruct          */
  27.     char szBuff[30];       /* buffer for message box       */
  28.     BOOL freed;           /* return value from GlobalFree */
  29.  
  30.     /* allocate space in global heap for a MYSTRUCT structure */
  31.     hMemBlock = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE,
  32.                             (long)sizeof(MYSTRUCT));
  33.  
  34.     /* if memory allocated properly */
  35.     if (hMemBlock != NULL)
  36.        {
  37.        /* lock memory into current address */
  38.        ThisPtr = (lpMyPtr)GlobalLock(hMemBlock);
  39.  
  40.     /* if lock worked */
  41.     if (ThisPtr != NULL)
  42.        {
  43.        /* use memory from global heap and output results*/
  44.        ThisPtr->x = 4;
  45.        ThisPtr->y = 4;
  46.        ThisPtr->x = ThisPtr->x*ThisPtr->y;
  47.        sprintf(szBuff,"ThisPtr->x * ThisPtr->y = %d",ThisPtr->x);
  48.        MessageBox(GetFocus(),(LPSTR)szBuff,
  49.                      (LPSTR)"Info from GlobalAlloc'ed memory",
  50.                      MB_OK);
  51.        GlobalUnlock(hMemBlock);          /* unlock memory */
  52.  
  53.        freed = GlobalFree(hMemBlock);    /* free memory */
  54.        if (!freed)  /* if memory freed */
  55.        MessageBox(GetFocus(),(LPSTR)"The memory was freed properly",
  56.                  (LPSTR)" ",MB_OK);
  57.        else      /* if memory not freed */
  58.        MessageBox(GetFocus(),(LPSTR)"The memory WAS NOT freed",
  59.                   (LPSTR)" ",MB_OK);
  60.        }
  61.    }
  62.     return 0;
  63. }
  64.