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

Apple Remote Desktop Client 3.9.3 - Clie...
Apple Remote Desktop Client is the best way to manage the Mac computers on your network. Distribute software, provide real-time online help to end users, create detailed software and hardware reports... Read more
jAlbum Pro 14.0 - Organize your digital...
jAlbum Pro has all the features you love in jAlbum, but comes with a commercial license. You can create gorgeous custom photo galleries for the Web without writing a line of code! Beginner-friendly... Read more
jAlbum 14.0 - Create custom photo galler...
With jAlbum, you can create gorgeous custom photo galleries for the Web without writing a line of code! Beginner-friendly, with pro results - Simply drag and drop photos into groups, choose a design... Read more
Vitamin-R 2.48 - Personal productivity t...
Vitamin-R creates the optimal conditions for your brain to work at its best by structuring your work into short bursts of distraction-free, highly focused activity alternating with opportunities for... Read more
Beamer 3.3 - Stream any movie file from...
Beamer streams to your Apple TV.... Plays any movie file - Just like the popular desktop movie players, Beamer accepts all common formats, codecs and resolutions. AVI, MKV, MOV, MP4, WMV, FLV. To... Read more
Shredo 1.2.2 - $9.99
Shredo is a beautiful, functional file-shredding and privacy scan utility. It permanently shreds files, folders, and external volumes' contents to keep information secure and impossible for anyone to... Read more
Final Draft 10.0.3 - Industry-leading sc...
Final Draft allows you to use your creative energy to focus on the content; let Final Draft take care of the style. Final Draft is the number-one selling application specifically designed for writing... Read more
Google Chrome 59.0.3071.109 - Modern and...
Google Chrome is a Web browser by Google, created to be a modern platform for Web pages and applications. It utilizes very fast loading of Web pages and has a V8 engine, which is a custom built... Read more
Chromium 59.0.3071.109 - Fast and stable...
Chromium is an open-source browser project that aims to build a safer, faster, and more stable way for all Internet users to experience the web. Version 59.0.3071.109: This update has no Flash plug-... Read more
iShowU Instant 1.1.8 - Full-featured scr...
iShowU Instant gives you real-time screen recording like you've never seen before! It is the fastest, most feature-filled real-time screen capture tool from shinywhitebox yet. All of the features you... Read more

Latest Forum Discussions

See All

Solve the disappearance of history’s gre...
Blue Brain Games invites you to indulge in an immersive hands-on 3D puzzle adventure in similar vein to The Room series, with its debut release The House of Da Vinci. Set during the historic period of the Italian Renaissance (when Leonardo himself... | Read more »
Age of Rivals (Games)
Age of Rivals 3.3 Device: iOS Universal Category: Games Price: $.99, Version: 3.3 (iTunes) Description: Deep civilization-building strategy in a fast-paced card game! | Read more »
Panthera Frontier (Games)
Panthera Frontier 1.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0 (iTunes) Description: | Read more »
Angry Birds Evolution beginner's gu...
Angry Birds changes things up a fair bit in its latest iteration, Angry Birds Evolution. The familiar sling-shot physics mechanics are still there, but the game now features team-based gameplay, RPG elements, and a new top-down view. With all of... | Read more »
Sega Forever is for the retro game fans
Sega is launching a new retro games service titled Sega Forever, in a move that's sure to delight games enthusiasts with a bit of nostalgia. Sega's releasing five classic games for free. The titles include Sonic the Hedgehog, Phantasy Star II,... | Read more »
The Little Acre (Games)
The Little Acre 1.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: | Read more »
Lovely adventure game 'The Little A...
The Little Acre makes its way from PC to iOS today and it's a real charmer. It's a lovely little adventure game set in 1950's Ireland, gorgeously animated in a style slightly reminiscent of old Disney films. The game won a lot of praise for its... | Read more »
Futurama: Worlds of Tomorrow officially...
Futurama: Worlds of Tomorrow arrives next Thursday, and it features . . . Stephen Hawking? Turns out a few of your favorite science super stars, including Bill Nye, Neil DeGrasse Tyson, and George Takei will be making an appearance alongside the... | Read more »
MU Origin’s new update offers exciting c...
MU Origin is kicking off the summer with style. Its latest update is a real doozy, offering up plenty of fresh content. New challenges, some extra help for newcomers, and new costumes are just a few of the things you will find in the new patch. | Read more »
Pokémon GO introduces Raid Battles and a...
If you were hoping to conquer any gyms today in Pokémon GO you're in for a bit of disappointment. Niantic has closed gyms in the game to prepare for a huge upcoming update that is going to complete change Pokémon GO's competitive elements. The... | Read more »

Price Scanner via

Clearance 2016 MacBook Pros available for up...
B&H Photo has clearance 2016 13″ and 15″ MacBook Pros in stock today and on sale for up to $400 off original MSRP. Shipping is free, and B&H charges NY & NJ sales tax only: - 15″ 2.7GHz... Read more
Apple Ranks 9th In comScore Top 50 U.S. Digit...
comScore, Inc. has released its monthly ranking of U.S. online activity at the top digital media properties for May 2017 based on data from comScore Media Metrix Multi-Platform. * Entity has... Read more
10.5-inch iPad Pros available for up to $20 o...
B&H Photo has the new 2017 10.5″ iPad Pros available for up to $20 off MSRP including free shipping plus NY & NJ sales tax only: - 64GB iPad Pro WiFi: $649 - 256GB iPad Pro WiFi: $749 - 512GB... Read more
Three Off-The-Beaten-Track iOS Apps That Dese...
One of the great things about using iPads and iPhones is the vast selection of apps available for most anything you want or need to do. The three outlined in this article have been in my core app... Read more
Apple No. 1 Spot In Gartner Top 100 Vendors i...
Gartner, Inc. has unveiled the top global 100 vendors in IT in 2016 based on their revenue across IT (excluding communication services) and component market segments. In the Gartner Global Top 100:... Read more
Clearance iMacs available for up to $300 off...
B&H Photo has clearance 21″ and 27″ Apple iMacs available starting at $949, each including free shipping plus NY & NJ sales tax only: - 27″ 3.3GHz iMac 5K: $1999 $300 off original MSRP - 27″... Read more
1.4GHz Mac mini, refurbished, available for $...
The Apple Store has Apple Certified Refurbished 1.4GHz Mac minis available for $419. Apple’s one-year warranty is included, and shipping is free. Their price is $80 off MSRP, and it’s the lowest... Read more
Free Mixoo iOS Photo Editing App Gets Major U...
Button Software Technology has announced Mixoo 3.0, an important feature update to the company’s photo editor for iOS devices. Mixoo offers amazing ways to edit as well as decorate personal photo... Read more
FNable 2.0 Function Key Enabling Software Get...
Briksoftware has released FNable 2.0 With Touch Bar Support, a major new version of the function key enabling software now compatible with Touch Bar keyboards. FNable’s simplicity that allows users... Read more
Clearance 2016 12-inch Retina MacBooks, Apple...
Apple recently dropped prices on Certified Refurbished 2016 12″ Retina MacBooks, with models now available starting at $1019. Apple will include a standard one-year warranty with each MacBook, and... Read more

Jobs Board

Product Manager, *Apple* News - Apple Inc....
…on new product areas, many of which have great potential impact to Apple .Drives the definition of broad, complex, and high impact products for worldwide markets, Read more
Sr. Software Engineer, *Apple* Online Store...
…building high throughput, high performance, reliable, checkout & payment platform that support Apple online stores. You will be working with the latest in services Read more
Product Owner, *Apple* Communities - Apple...
…for managing and delivering a world-class community experience to Apple 's customers. Your primary responsibilities include developing internal-facing tools, Read more
*Apple* Customer Experience (ACE) Leader - A...
…management to deliver on business objectivesTraining partner store staff on Apple products, services, and merchandising guidelinesCoaching partner store staff on Read more
Pan Europe Market Development Manager %u2014...
…local artists across the region.* Building strong relationships with local Apple teams & collaborating on mutually beneficial projects.* Building strong Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.