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

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