TweetFollow Us on Twitter

Heap Zones
Volume Number:3
Issue Number:1
Column Tag:ABC's of C

Peeking at Heap Zones

By Bob Gordon, Contributing Editor

Memory is the stuff of which there never is enough. To reduce problems due to lack of memory, most languages provide means to grab some memory for use and later release it. Standard C has a number of functions to manage memory allocation and deallocation. We are not going to discuss these in any detail because the Macintosh has a complete memory management system. We have been using the memory management routines indirectly every time we opened a window, but as we go further into Mac programming we need to manipulate memory directly.

Figure 1: Examining the heap

Macintosh Memory Organization

Just about every book on programming the Macintosh has pictures of the Macintosh memory map. For the 64K ROMS, it looks roughly like:

I left off the physical addresses because they are typically not important, and because many of them can change as a function of memory size. For the 128K ROMS, the arrangement is slightly different. The ROM trap dispatch table has been expanded and is now in two sections, with the second section between the system heap and the second system globals area.

For this discussion, the most important areas are the Application Heap and the Stack. The stack is where all C parameters and local variables reside (actually, this depends on the compiler. Some compilers will pass some parameters in registers, and programmers may specify variables to be register variables, and if a register is available, the variable will be placed in a register). The stack grows and shrinks with the function calls and returns.

The application heap is the area where memory is explictly reserved and released. Unlike the stack, memory reserved in the heap does not disappear when a function returns. This allows the creation of large, complex data structures "on the fly."

C Memory Allocation

Since C is used on systems other than the Mac (really, there are other computers!), you might want to know about the standard C memory functions.

malloc() allocates some memory. It receives one parameter, the number of bytes to allocate, and returns a pointer to the region of memory.

free() deallocates memory previously allocated. It receives one parameter, a pointer previously returned by malloc().

The actual names and implementation will vary somewhat by compiler. Lightspeed C provides eight allocation functions and five deallocation functions in its standard library. Most of these are there to provide compatibility with Unix. The other Macintosh C compilers with which I am familiar also provide the standard C functions.

Unless you are using your Mac to develop software to run on another system, it is not a good idea to use the standard C memory functions. The primary reason for this is that on the Mac there are two kinds of allocated memory, relocatable and non-relocatable. None of the C compilers I have seen make any attempt to relate the standard C memory functions to the Mac memory functions (I assume the standard C functions return pointers to non-relocatable blocks of memory, but this is not made apparent).

Macintosh Memory Allocation

Again, since information about the Mac memory management system is readily available, I am not going to attempt to cover all the details here. There are, however, several key concepts which probably deserve some attention.

As mentioned above, memory comes in two kinds, relocatable and nonrelocatable. A relocatable block may be moved around in the heap by the operating system to make room for additional allocations. Since it may be moved, you do not receive a pointer to the block but a handle that points to a master pointer that points to the block.

Since the master pointer does not move (it is nonrelocatable), the value of the handle remains constant. When you request a nonrelocatable block, you receive a pointer directly to the block since the operating system will not move it. In general it seems that relocatable blocks are preferred since the operating system can move them out of the way when needed. If there are many nonrelocatable blocks, the operating system may not be able to satisfy a memory request because there may be no single space available big enough to meet the need. Without the ability to move blocks in the heap around (compact the heap), you will run out of memory sooner.

One problem with relocatable blocks is that it takes two pointers to access the data. One can always obtain a pointer to the block, but the system may move the block while you are using it. This situation, known as a dangling pointer, can cause quite exciting and hard to diagnose problems. If you need to use a particular block a lot in a function, you may lock the block which makes it temporarily nonrelocatable. Be sure to unlock it when you are done.

Another option for relocatable blocks is to purge them from memory. The operating system will do this if it needs more memory than is available, but only if you have marked a block as purgeable. New relocatable blocks start out as not purgeable. Note that if a block is purged, you will still have the handle, but the pointer it contains will be set to zero. To reuse the block, it is necessary to reallocate the block and rebuild the data. There is a function that reallocates purged blocks; the data is the programmer's responsibility.

Memory management errors are available through the function MemError(). A value of zero (NoErr) means there was no error; negative values represent error codes.


There were a few changes to printw. We have added the ability to print rectangle and point coordinates. This is useful when using graphics. This time I added hex output. It is also now a seperate file. I have found it useful, but we probably won't print the whole thing again after this month, since this is the second time we've seen this routine.

The Program

Our program this month makes a number of trap calls that deal with memory management. From these calls, we can display information about the application heap and see how the creation of handles and pointers affects the available heap space. To keep things simple, we have created a very minimal Mac program that just puts up a blank window. The real heart of the program is the memory functions menu that lets us create handles and pointers and free them so we can see the effect on the heap. Fig. 1 shows how we print the memory information in our debugging print window using the printw() routine we learned about in a previous issue of MacTutor.

When you run the program, use the Zone Info menu item to see the state of the heap. I left the abc window in (under the File menu). Make a window and then run Zone Info. The Show Zone item traces through the zone and gives a line of information about each block, telling if it is free, relocatable or non-relocatable. By the way, the information needed to trace through the heap is not ordinarily available so there is a structure defined just before main() that defines the information needed to understand the heap. This structure, called memheads, is actually the definition of a block header. The other menu items create handles and pointers using NewHandle and NewPtr, and then if the handle or pointer is valid, another menu item lets us dispose of those handles and pointers, using DisposHandle and DisposPtr. The Zone Info menu item should show the effect of each of these operations on the available space in the heap.

There is another "feature" to this program. Every time you reserve a relocatable block, the size reserved doubles. With zone info, you can watch the memory manager increase the size of the heap and eventually run out of memory.

The key to the program is the GetZone trap call. This returns a pointer to the current heap zone. Once we have this pointer, our ShowZone and CountZone routines will read and print information about the zone for us. See the domem(item) routine in the listing to see where this trail starts with the memory menu item.

The term zone is how the heap is divided. Each zone in the heap is divided into blocks. A block is an even number of bytes, the minimum of which is 12. When your application starts up, call MaxApplZone to expand the application heap zone to its limit. Normally, an application would only be concerned with a single heap zone for itself, but you can create additional zones in the heap. One of our menu items does call MaxApplZone so you can see if it has any effect depending on when you call it. We can find out the free space left in a heap zone by calling FreeMem.

Once we get a pointer to the current heap zone, then we can examine the zone. A heap zone contains a 52 byte zone header, the allocated blocks within the zone, and a final minimum size block at the end of the zone called the zone trailer. The zone header is a pascal record defined below:

 bkLim: Ptr;{zone trailer block}
 purgePtr:Ptr;   {used internally}
 hFstFree:Ptr;   (first free master pointer}
 zcbFree: LONGINT; {number of free bytes}
 gzProc:ProcPtr; {grow zone function}
 moreMast:Integer; {master pointers to allocate}
 flags: Integer; {used internally}
 cntRel:Integer; {not used}
 maxRel:Integer; {not used}
 cntNRel: Integer; {not used}
 maxNRel: Integer; {not used}
 cntEmpty:Integer; {not used}
 cntHandles:Integer; {not used}
 minCBFree: LONGINT; {not used}
 purgeProc: ProcPtr; {purge warning proc}
 sparePtr:Ptr;   {used internally}
 allocPtr:Ptr;   {used internally}
 heapData:Integer{first usable byte in zone}

The zone pointer is defined to be of type THz, which is simply declared to be ^Zone. HeapData is the first two bytes in the block header of the first block in the zone. Hence to find the first usable block, we can say @(myZone^.heapData), which is a pointer to the first block header. Or in c, we would use &zone->heapData. The block header is 8 bytes: the tag byte, a three byte block size, and a four byte identifier that indicates whether the block is relocatable, non-relocatable or free. The four byte identifier is actually a handle, pointer or unused depending on the nature of the block. The tag byte also contains information on the nature of the block in bits 6 and 7. We can examine the nature of every block in the heap zone by adding the block size to the address of the first block and going from block to block checking the two high order bits of the tag byte. All of this is discussed in great detail in the IM chapter on the memory manager. This is implemented in our program in the showzone(zone) routine. Our memhead structure actually combines the tag byte and block size into a single four byte field called physsize. The second four bytes in the block header are stored in our memhead structure in the relhand field. We decode the physsize field to obtain the tag byte, and the block size, then we break down the tag byte to obtain the block status, and the size correction. All of this is done in the showhead(head) routine. Study carefully the three routines showhead, showzone and countzone to see how the block headers are decoded and the block size, status and address are then printed in our print window.

Final Comments

Using the techniques shown in this program, you can construct your own heapshow utility or TMON heap display. A good discussion of how TMON examines and displays the heap, is available in Dan Weston's new book, Macintosh Assembly Language Programming, Vol. II. There are some useful memory management functions not included this month such as MoreMasters() which reserves space for master pointers needed by NewHandle(). These should be easy to include in the program if you need to get an idea of how they work.

Next time we'll return to quickdraw and try to draw polygons, regions, and pictures.

Figure 4: ShowZone gives a heap dump

/* mem.c
 * explore memory allocation
 * LS C by Bob Gordon

 #include "abc.h"
 #include "MemoryMgr.h"
 #include "Quickdraw.h"
 #include "EventMgr.h"
 #include "WindowMgr.h"
 #include "MenuMgr.h"
 #include "FontMgr.h"
 /* defines for menu ID's */
 #defineMdesk    100
 #defineMfile    101
 #defineMedit    102
 /* File */
 #defineiClose   2
 #defineiQuit    3
 /* Edit */
 #defineiUndo    1
 #defineiCopy    4
 #defineiPaste   5
 /* Memory */
 #defineiZone    1
 #defineiMzone   2
 #defineiInfo    3
 #defineiHand    4
 #defineiFreeH   6
 #defineiFreeP   7
 /* Global variables */
 MenuHandle menuDesk;/* menu handles */
 MenuHandle menuFile;
 MenuHandle menuEdit;
 MenuHandle menuMem;
 WindowRecord  windowRec;
 Rect   dragbound;
 Rect   limitRect;
 * structure needed to examine heap not typically
 * supplied by Mac development systems because normal
 * applications do not need to examine the heap. 
 struct memheads
 long   physsize;
 long   relhand;
 initsys(); /* sys init */
 initapp(); /* appl init */

/* system initialization  */
 theWindow = Nil;/* no window */

 * application initialization
 * Sets up menus.*/

 * set up application's menus
 * Each menu is a separate group
 * of lines.  
 menuDesk = NewMenu(Mdesk,CtoPstr("\24"));
 AddResMenu (menuDesk, 'DRVR');
 InsertMenu (menuDesk, 0);
 menuFile = NewMenu(Mfile, CtoPstr("File"));
 AppendMenu (menuFile, 
 InsertMenu (menuFile, 0);
 menuEdit = NewMenu(Medit, CtoPstr("Edit"));
 AppendMenu (menuEdit, 
 InsertMenu (menuEdit, 0);
 menuMem = NewMenu(Mmem, CtoPstr("Memory"));
 AppendMenu (menuMem,
 CtoPstr("Show Zone;Max Zone;Zone Info;New Handle;New Pointer"));
 AppendMenu (menuMem,CtoPstr("Free Handle;Free Pointer"));
 InsertMenu (menuMem, 0);
/* Event Loop 
 * Loop forever until Quit
 char   c;
 short  windowcode;
 if (theWindow)      /* this code is here to */
 { /* prevent closing an */
 EnableItem(menuFile,2);  /* already closed window */
 if (GetNextEvent(everyEvent,&theEvent))
 { /* only check mouse */
 case mouseDown:

/* domousedown
 * handle mouse down events
 short  windowcode;
 short  ingo;
 long   size;
 long   newsize;
 RgnPtr rp;
 Rect   box;
 Rect   *boxp;
 windowcode = FindWindow(er->where, &whichWindow);
 switch (windowcode)
 case inDesk:
 if (theWindow notequal 0)
 HiliteWindow(theWindow, False);
 case inMenuBar:
/* domenu
 * handles menu activity
 * simply a dispatcher for each
 * menu.
 long   mc; /* menu result */
 short  menuId;
 short  menuitem;
 menuId = HiWord(mc);
 menuitem = LoWord(mc);
 switch (menuId)
 case Mdesk : break; /* not handling DA's */
 case Mfile : dofile(menuitem);
 case Mmem  : domem(menuitem);

 short  item;
 THz    zone;
 static longsize = 1024;
 static Handle   hand = 0;
 static Ptr ptr = 0;
 struct memheads *memhead;
 switch (item)
 case iZone :
 zone = GetZone();
 printw("\nzone %ld ",zone);
 case iMzone :
 case iInfo :
 zone = GetZone();
 case iHand :
 hand = NewHandle(size);
 printw("\nhandle %ld pointer %lx error %d ",hand,*hand,MemError());
 printw(" free mem %ld ",FreeMem());
 size = size * 2;
 case iPtr :
 ptr = NewPtr(size);
 printw("\npointer %ld error %d free mem %ld",ptr,MemError(),FreeMem());
 case iFreeH :
 if (hand equals 0)
 printw("\nNo current handle to free");
 hand = 0;
 case iFreeP :
 if (ptr equals 0)
 printw("\nNo current pointer to free");
 ptr = 0;

 struct memheads *head;
 uchar  tagbyte;
 printw ("\naddress %ld ",(char*)head + 8);
 tagbyte = head->physsize >> 24;
 printw ("size correction %d ",tagbyte & 0xF);
 tagbyte >>= 6;
 switch (tagbyte)
 case 0:
 printw(" free block ");
 case 1:
 printw(" non rel    ");
 case 2:
 printw(" rel        ");
 printw(" physical size %ld ",head->physsize & 0x00FFFFFF);
 return (tagbyte);

 THz    zone;
 struct memheads *memhead;
 short  tblocks = 0;
 short  tfree = 0;
 short  trl = 0;
 short  tnonrel = 0;
 memhead = (struct memheads*)&zone->heapData;
 while (memhead < (struct memheads*)zone->bkLim)
 switch (showhead(memhead))
 case 0 : tfree++; break;
 case 1 : tnonrel++; break;
 case 2 : trel++; break;
 memhead = (struct memheads*)((char*)memhead + (memhead->physsize & 0x00FFFFFF));
 printw("\n blocks %d free %d relocatable %d non-relocatable %d ",
   tblocks, tfree, trel,tnonrel);
 THz    zone;
 struct memheads *memhead;
 short  tblocks = 0;
 short  tfree = 0;
 short  trel = 0;
 short  tnonrel = 0;
 uchar  tagbyte;
 memhead = (struct memheads*)&zone->heapData;
 while (memhead < (struct memheads*)zone->bkLim)
 tagbyte = memhead->physsize >> 24;
 tagbyte >>= 6;
 switch (tagbyte)
 case 0 : tfree++; break;
 case 1 : tnonrel++; break;
 case 2 : trel++; break;
 memhead = (struct memheads*)((char*)memhead + (memhead->physsize & 0x00FFFFFF));
 printw("\n blocks %d free %d relocatable %d non-relocatable %d ",
   tblocks, tfree, trel, tnonrel);
/* dofile
 * handles file menu
 short  item;
 char   *title1; /* first title for window */
 Rect   boundsRect;
 switch (item)
 case iNew :/* open the window */
 title1 = "ABC Window";
 theWindow = NewWindow(&windowRec, &boundsRect,
 (WindowPtr) -1, True, 0);
 case iClose :   /* close the window */
 theWindow = Nil;
 case iQuit :    /* Quit */

Community Search:
MacTech Search:

Software Updates via MacUpdate

Adobe Acrobat Reader 15.009.20069 - View...
Adobe Acrobat Reader allows users to view PDF documents. You may not know what a PDF file is, but you've probably come across one at some point. PDF files are used by companies and even the IRS to... Read more
Adobe Acrobat Pro 15.009.20069 - Powerfu...
Acrobat Pro DC is available only as a part of Adobe Creative Cloud, and can only be installed and/or updated through Adobe's Creative Cloud app. Adobe Acrobat Pro DC with Adobe Document Cloud... Read more
Path Finder 7.2 - Powerful, award-winnin...
Become a master of file management with Path Finder. Take full control over your file system. Save your time: compare and synchronize folders, view hidden files, use Dual Pane and full keyboard... Read more
Sid Meier's Civilization: Beyond Ea...
Sid Meier's Civilization: Beyond Earth is a new science-fiction-themed entry into the award-winning Civilization series. Set in the future, global events have destabilized the world leading to a... Read more
ForkLift 2.6.6 - Powerful file manager:...
ForkLift is a powerful file manager and ferociously fast FTP client clothed in a clean and versatile UI that offers the combination of absolute simplicity and raw power expected from a well-executed... Read more
Microsoft Remote Desktop 8.0.21 - Connec...
With Microsoft Remote Desktop, you can connect to a remote PC and your work resources from almost anywhere. Experience the power of Windows with RemoteFX in a Remote Desktop client designed to help... Read more
OnyX 3.1.0 - Maintenance and optimizatio...
OnyX is a multifunctional utility for OS X. It allows you to verify the startup disk and the structure of its System files, to run miscellaneous tasks of system maintenance, to configure the hidden... Read more
Spotify - Stream music, crea...
Spotify is a streaming music service that gives you on-demand access to millions of songs. Whether you like driving rock, silky R&B, or grandiose classical music, Spotify's massive catalogue puts... Read more
ExpanDrive - Access cloud storag...
ExpanDrive builds cloud storage in every application, acts just like a USB drive plugged into your Mac. With ExpanDrive, you can securely access any remote file server directly from the Finder or... Read more
Markly 1.5.3 - Create measurement and de...
Markly is a measurement and design-spec plugin/extension for Photoshop and Sketch. It is made for modern Web designers and app front-end developers. You can add specification marks simply by clicking... Read more

Max Ammo - Tricks and tips to help you l...
Max Ammo is a smart cover shooter in which you have to fight back against the Reptor Empire, a race of alien lizards who have invaded your home. You'll have to tap to shoot, swipe to get into cover, and upgrade your gear if you plan on surviving... | Read more »
Balls & Holes - Tips and tricks to h...
Balls & Holes is a gorgeous new endless runner that challenges you to make it as far up a mountain as possible before inevitably being sliced into a load of gooey bits. Making this task more difficult are both the wide variety of balls that... | Read more »
Balloony Land offers a fresh twist on th...
Balloony Land by Palringo offers a fresh twist on the match three genre and is out now on iOS and Android. First-off, you'll be popping balloons instead of crushing candy and the balloons will float up and fill the empty spaces instead of dropping... | Read more »
Graphic - vector illustration and design...
Graphic - vector illustration and design 1.0 Device: iOS iPhone Category: Productivity Price: $2.99, Version: 1.0 (iTunes) Description: Autodesk Graphic is a powerful full-featured vector drawing and illustration application right in... | Read more »
Sago Mini Babies (Education)
Sago Mini Babies 1.0 Device: iOS Universal Category: Education Price: $2.99, Version: 1.0 (iTunes) Description: Introducing the Sago Mini babies. Boys and girls love caring for these adorable characters. Feed Robin her favorite mush... | Read more »
PAUSE - Relaxation at your fingertip (H...
PAUSE - Relaxation at your fingertip 1.1 Device: iOS iPhone Category: Healthcare & Fitness Price: $1.99, Version: 1.1 (iTunes) Description: | Read more »
Super Sharp (Games)
Super Sharp 1.1 Device: iOS Universal Category: Games Price: $1.99, Version: 1.1 (iTunes) Description: Your finger has never been so sharp! Cut with skill to complete the 120 ingenious physics levels of Super Sharp and become a cut... | Read more »
Assembly - Graphic design for everyone...
Assembly - Graphic design for everyone 1.0 Device: iOS Universal Category: Photography Price: $2.99, Version: 1.0 (iTunes) Description: Assembly is the easiest most powerful design tool on the App Store. Create anything you can... | Read more »
Dub Dash (Games)
Dub Dash 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: ARE YOU READY FOR THE ULTIMATE CHALLENGE? UNIQUE SYMBIOSIS OF MUSIC AND GRAPHICS | Read more »
Leave Me Alone (Games)
Leave Me Alone 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: 33% off launch sale!!! Somewhere between the 1980s and 1990s there exists a world that never was. A world of skatepunks,... | Read more »

Price Scanner via

Adobe and Dropbox Partner to Streamline Work...
Adobe and Dropbox Inc. have announced a partnership to enable people and organizations greater flexibility to work the way they want with documents at home, in the office or on-the-go. The companies... Read more
DriveSavers Offers Data Recovery Relief to Vi...
DriveSavers, specialists in data recovery, eDiscovery and digital forensic services have announced assistance to victims of the recent storm and historically unprecedented flooding in South Carolina... Read more
Apple Products Four Of 2015′s Top Ten Most Wa..., Future’s global technology brand and the UK’s biggest technology website, has unveiled results from extensive research that show • The Smart Home is what excites the public most about... Read more
13-inch 2.7GHz/128GB Retina MacBook Pro on sa...
Best Buy has the 13″ 2.7GHz/128GB Retina MacBook Pro on sale for $1174.99 for a limited time. Choose free shipping or free local store pickup (if available). Sale price for online orders only, in-... Read more
App Tamer 2.1 Makes El Capitan Cooler, Quiete...
St. Clair Software has announced the availability of a free update to its App Tamer utility for Mac OS X. App Tamer 2.1 delivers compatibility with Yosemite and improves its support for a number of... Read more
15-inch Retina MacBook Pros on sale for up to...
B&H Photo has 2015 15″ Retina MacBook Pros on sale for up to $160 off MSRP including free shipping plus NY sales tax only: - 15″ 2.2GHz Retina MacBook Pro: $1849.99 $150 off - 15″ 2.5GHz Retina... Read more
12-inch Retina MacBooks on sale for $100 off...
Best Buy has 12″ Retina MacBooks available for $100 off MSRP on their online store. Choose free shipping or free local store pickup (if available). Discounted prices available for online orders only... Read more
MacBook Airs on sale for up to $100 off MSRP
Save up to $100 on the purchase of a new 2015 13″ or 11″ 1.6GHz MacBook Air at the following resellers. Shipping is free with each model: 11" 128GB MSRP $899 11" 256GB... Read more
Save 15% with Apple refurbished Mac Pros
The Apple Store has Apple Certified Refurbished Mac Pros available for up to $600 off the cost of new models. An Apple one-year warranty is included with each Mac Pro, and shipping is free. The... Read more
Apple restocks refurbished Mac minis for up t...
Apple has restocked Certified Refurbished 2014 Mac minis, with models available starting at $419. Apple’s one-year warranty is included with each mini, and shipping is free: - 1.4GHz Mac mini: $419 $... Read more

Jobs Board

*Apple* Desktop Analyst - KDS Staffing (Unit...
…work with some of the brightest engineers. Job Description Title: Apple Desktop AnalystPosition Type: Full-time PermanentLocation: White Plains, NYHot Points:Depth of Read more
*Apple* Systems Engineer (Mclean, VA and NYC...
Title: Apple Systems Engineer (Mclean, VA and NYC) Location: United States-New York-New York-NYC 200 Park Avenue (22005) Other Locations: United Read more
Partner Business Development Manager - *Appl...
…exceptional individuals to join our Sales Solutions team as Business Development Manager- Apple . This position focuses on the overall management of and achievement of Read more
Project Manager: *Apple* Pay - Apple (Unite...
…The iOS Systems team is looking for a project manager who will manage Apple Pay server side integration project resources in a matrix organization, track tasks, prepare Read more
*Apple* Retail - Multiple Positions (US) - A...
Job Description:SalesSpecialist - Retail Customer Service and SalesTransform Apple Store visitors into loyal Apple customers. When customers enter the store, you're Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.