TweetFollow Us on Twitter

More Debugging Tips
Volume Number:12
Issue Number:11
Column Tag:Programming Techniques

Simple Yet Effective Bug Detection

Detecting and preventing common programming errors

By Lloyd Chambers, Senior Manager/Software Development,

Note: Source code files accompanying article are located on MacTech CD-ROM or source code disks.

Introduction

Most programmers are familiar with polling versus notification. Polling is when you continually scan for events to process until you find something of interest; notification is when you are told that there is something important to attend to, and unless there is something to attend to, you can use the time for something else. Polling is inefficient and wastes resources; notification is a far superior approach because you only expend effort as needed.

While programmers agree that polling is undesirable, few of them would be willing to admit that’s what they do everyday when they debug code-they poll for bugs until they find one by running the debugger, reading code, etc. This article discusses how to eliminate the old, inefficient polling paradigm of finding bugs with a new paradigm of bug notification.

This new bug-notification paradigm doesn’t apply to all types of bugs, but it does apply to a certain class of bugs that can be systematically eliminated while imposing little or no additional burden on the programmer. The three types of programming errors commonly responsible for a large number of bugs are: (1) invalid routine parameters, (2) failure to detect errors, and (3) memory leaks.

This article is divided into four major areas of interest:

• how to set up a debugging system;

• how to create and use asserts;

• how to create debugging versions of system calls;

• how to detect memory leaks.

You will want to read this article from start to finish as later techniques build on earlier ones.

This article avoids discussing techniques that require significant changes in coding style, extra work on the part of programmer or more than beginner-level concepts to use properly. Other techniques can be useful but offer limited “bang for the buck,” especially for beginning programmers. The techniques discussed here will be invaluable to all programmers regardless of experience.

The techniques discussed in this article could apply to any environment, though the implementations shown are for C and C++ environments. The provided sample code should be easy to retrofit into existing C or C++ projects. Complete implementations are not provided with this article, but enough functionality is provided to be quite useful “as is.”

Setting up a debugging system

Before moving into specific debugging techniques, we need to discuss how debugging code in general should be implemented. There are two general requirements debugging code must meet-it must be able to detect and report programming errors, and it must be easy to remove it from the product without altering source code.

Debugging code must be able to report programming errors. A reporting system can be simple or elaborate. At Symantec, we have chosen a simple system that is suitable for use in any type of code whether it be an application, INIT, driver, etc. More elaborate reporting systems can be devised, but they may then become limited in their applicability to certain types of code and may themselves interfere with the ability to debug code. Consequently, our basic reporting mechanism is a debugger break. Though it is primitive, it does the job, and it is simple, non-intrusive, and applicable to all types of code. Note that a high-level debugger which allows you to step through code is not a system to detect bugs- rather it is a tool you use to poll for bugs.

The second requirement of a bug detection system is that it can be removed from the final product so that it causes no run-time overhead. This leads to the building of a “debug” version and a “non-debug” version. The debug version may run more slowly and will be larger due to the additional debugging code; however, the debugging code disappears when a non-debug version is produced. When these two requirements are met, the programmer can detect bugs, yet the end-user realizes full performance from the product. It is important to realize that the mechanisms discussed here are focused on detecting programmer errors, not runtime errors that can reasonably be expected to occur. As such, all the mechanisms discussed are appropriate for a debug, testing version targeted at helping the programmer eliminate bugs from code. The mechanisms discussed here are not intended as an error handling mechanism for your program; those sorts of things must be handled using other techniques, and ultimately may involve reporting problems to the end-user.

The DEBUG flag

Compiling a debug or non-debug program is best done using a compiler flag. We define a flag called DEBUG. In most programming environments, you can define such a flag in a prefix file which will be included for all source files. With multiple projects, you can have each project prefix file include a shared file which defines the DEBUG flag. In this way, you can exercise global control at build time over whether a debug or non-debug version is built, even if your product consists of dozens of modules. The DEBUG flag should be defined as 0 for debugging to be off, and 1 if it should be on:

 #define DEBUG 1 // debugging on 

All debugging code not intended for the final project should be dependent upon this flag. Debugging macros should be defined to go away when DEBUG is off. Code that is debugging only should be conditionally compiled. For example:

 #if DEBUG
 #define DebugMsg( msg )  { DebugStr( msg ); }
 #else
 #define DebugMsg( msg )  {/*nothing*/}
 #endif

 #if DEBUG
    // debugging code here
 #endif

In addition, other more specific compiler flags may be dependent on the DEBUG flag. In general, if you have a specific debugging module, you’ll want to use a flag for it which is dependent on the DEBUG flag. This is useful to selectively enable or disable certain debugging capabilities without disabling other debugging capabilities. By default, it could be the same as the DEBUG flag, but could also be set differently. For example:

 #if DEBUG
    #define USE_DEBUG_TRAPS 1    // on or off as desired
 #else
    #define USE_DEBUG_TRAPS 0    // always off when DEBUG off
 #endif

Creating and using Asserts

Now that we’ve discussed how to set up a debugging system, let’s move on to the basic building blocks most debugging code will use. Verifying program requirements is done using “assert” calls and related variants. Asserts allow the programmer to require and flag run-time conditions that do not meet program requirements. For example, a routine that takes a pointer may want to require that it be non-nil. Asserts are used in a number of programming environments and will differ from the implementation discussed here.

Asserts may be very simple or quite complex. They are best implemented as macros so that they can be compiled out of the code in a non-debug version. Note that a macro may call a routine, or may use inline code, depending on its complexity. Here are the asserts and related variants we commonly use at Symantec:

 
    // break with message if condition is false (zero)
 Assert( condition, failureMessage )

    // break with message if false; append number to it
 AssertNum( condition, failureMessage, theNumber )

    // break into debugger with message
 DebugMsg( message )

    // break with message if true (non-zero)
 DebugMsgIf( condition, message )

    // break with message; append number to it
 DebugNum( message, theNumber )

    // break with message if true; append number to it
 DebugNumIf( condition, message, theNumber )

For example, if you want to verify that a pointer is non-nil, you would write the following assert:

 Assert( thePointer != nil,
 “\pRoutineName: nil pointer”);

You can also use higher level asserts which perform a fair amount of computation to verify the assertion. In general, more complex asserts verify the integrity of a program entity. The following asserts break into the debugger with the specified message plus additional useful information when there is a problem:

    // break if the Handle is invalid
 AssertHandleIsValid( theHandle, failureMessage )

    // break if the Handle is invalid or not a resource
 AssertResourceIsValid( theResource, failureMessage )

    // break if the address is invalid
    // or not aligned to the specified boundary
 AssertAddressIsValid( addr, failureMessage )
 AssertAddressIsValidAlign( addr, alignBy, failureMsg )
 AssertAddressIsValidAlign2( addr, failureMsg )
 AssertAddressIsValidAlign4( addr, failureMsg )

    // break if ‘fsSpec’ is not a valid FSSpec
    // also displays FSSpec and describes why it is invalid
 AssertSpecIsValid( fsSpec, failureMsg )

    // break if ‘refNum’ is not a valid ref num
 AssertFileRefNumIsValid( refNum, failureMsg )

    // break if ‘upp’ is not a valid universal proc ptr (PPC)
 AssertUPPIsValid( upp, failureMsg )

    // break if ‘string’ is too long or too short
 AssertStringIsValid( string,
 minLength, maxLength, failureMessage )

    // break if ‘desc’ is invalid
 AssertAEDescIsValid( desc, failureMsg )

    // break if err is anything other than ‘noErr’ or a cancel
    // also displays the error code
 AssertNoErr( err, failureMsg );
 DebugIfErr( err, failureMsg );

How to declare Asserts and other debugging routines

Debug code should be defined to compile in when DEBUG is on, and compile to nothing when DEBUG is off. In the following example, the thing to notice is that when DEBUG is off, the macro is defined in such a way that no code is generated by the compiler:

#if DEBUG
 void _AssertHandleIsValid( const void *theHandle,
 const char  *varName, ConstString255Param msg );

 #define AssertHandleIsValid( h, msg ) \                       
 _AssertHandleIsValid( h, #h, msg );
#else
 #define AssertHandleIsValid(h, msg ){/*nothing*/}
#endif

You could also choose to define the routine as a normal function in a debug version and a macro that does nothing in a non-debug version. However, that approach is less flexible. For example, as a macro, AssertHandleIsValid calls _AssertHandleIsValid with an additional parameter generated by the preprocessor ‘#’ operator. Suppose your code looks like this:

 AssertHandleIsValid( myThing->itemList, “\pMyRoutine” );

The code actually seen by the compiler is as follows:

 _AssertHandleIsValid( itemList,
 “myThing->itemList”, “\pMyRoutine” );

The parameter varName is a C string which is the textual version of the parameter or expression. When AssertHandleIsValid detects an invalid Handle, it generates an error message describing the problem and incorporates this string into the error message. Note that some older development environments may not support the #x preprocessor directive.

An example Assert

_AssertHandleIsValid checks as many things as possible to verify the validity of the Handle. When a Handle can make it through this routine, it is highly probable that it is valid. If a problem is found, a detailed message describing the problem is generated and a debugger break is made.


 void
_AssertHandleIsValid(
 const void *    theHandle, 
    // void * avoids need to cast
 const char *    varName, 
    // a null terminated C string
 ConstStr255Parammsg)
 {
 OSErr  err;
 Str255 result;
 
 result[0]= 0;
 
 if ( IsNil( msg ) )
 {
 msg  = “\pAssertHandleIsValid()”;
 }
 
 _AssertAddressIsValidAlign( theHandle, varName, 4, msg);
 
    /*
    make a memory reference to force a crash here if the handle is invalid. It is better to force a crash 
    here, rather than crashing in some obscure place in the ROM later
    call a dummy routine to hopefully prevent compiler from optimizing out our  dereference.
    */

 MemoryDummy( *(short *)theHandle );
 
 (void)HandleZone( (Handle) theHandle );
 err  = MemError();
 if ( IsErr( err ) )
 {
 Str255 errStr;
 
 BuildBadAddressMsg( result,
 “\perror from HandleZone:”, varName, msg);
 
 DebugGetErrorString( err, errStr );
 AppendPString( “\p: “, result);
 AppendPString( errStr, result);
 
 DebugMsg( result );
 }
 
 if ( IsntNil( *(Handle)theHandle ) )
    // if it has a master pointer, then
    // check to see if we can get its size
 {
 (void)GetHandleSize( (Handle) theHandle );
 err  = MemError();
 if ( IsErr( err ) )
 {
 Str255 errStr;
 
 BuildBadAddressMsg( result,
 “\perror from GetHandleSize:”, varName, msg);
 
 DebugGetErrorString( err, errStr );
 AppendPString( “\p: “, result);
 AppendPString( errStr, result);
 
 DebugMsg( result );
 }
 }
 }

The following sample code generates the subsequent debugger breaks:

 Handle theHandle= nil;
 AssertHandleIsValid( theHandle, “\pmain”);
 
User break at 041B6268 _AssertAddressIsValidAlign+000AA
 NIL address: ‘theHandle’ [main]
User break at 041B637E _AssertHandleIsValid+000E6
 error from GetHandleSize: ‘theHandle’ [main]: nilHandleErr

Registering error codes

Some asserts display error codes. In the _AssertHandleIsValid example, shown above, DebugGetErrorString() is called to get a string for the error. Rather than display a raw number, such as -109, it’s often more convenient to see a string instead such as nilHandleErr. This is particularly nice when error codes change between revisions. And for less technical people, the message may be more easily remembered than a numeric error code. The supplied sample code implements this idea; see AddDefaultErrorStringTables() in Debug.c. You can also add your own error codes by calling DebugAddOSErrStringTable().

Using Asserts and their variants

We’ve now discussed how to create asserts. This next section discusses when to use them.

A common and critical place to use asserts is at the beginning of a program routines. All routines should be written using asserts to notify the programmer of illegal or questionable parameters. Depending on your overall design, your routines may or may not choose to check for illegal parameters in a non-debug version, but in a debug version there is no good reason for not detecting a client calling error. You will save your client (often yourself) much debugging effort if you fail an assert when an invalid call is made. In addition, asserts can often take the place of certain types of comments, which can become repetitive and out of date. Asserts cannot be out of date, since they are executable code that will complain if their requirements are not met.

It is important to remember that the primary purpose of asserts is to flag programming errors, not to handle problems that can arise naturally during programming execution. Handling of normal runtime errors is best handled through an error handling scheme, which of course is part of the final product. Asserts can be used to flag such conditions, but do not take the place of an error-handling scheme which prevents the program from crashing. You will probably want to use asserts and an error-handling scheme. If you use an error-handling scheme that silently cleans up without notification, you are not benefitting from bug detection. Also, it is unlikely that an error handling scheme will check anywhere near as stringently as an assert might. For example, your routine might reasonably be expected to check for a nil Handle, but only a DEBUG version would reasonably be expected to verify the integrity of the Handle as does AssertHandleIsValid.

The following sample routine documents its parameters well using asserts. If there are additional requirements for the parameters, they too should be documented using Asserts, particularly any non-obvious requirements. Note that the routine also flags any resulting error code. This may or may not be desirable, depending on whether you want to know about the error at this point. Often, flagging an error is a great idea, because the caller may not be checking the error result.

 OSErr
DoSomething
 (
 Handle theHandle,
 ConstString255Param fileName,
 void * buffer,
 UniversalProcPtrcallback,
 short  fileRefNum
 )
 {
 OSErr  err = noErr;

 AssertHandleIsValid( theHandle, “\pDoSomething”);
 AssertStringIsValid( fileName, 1, 31, “\pDoSomething”);
 AssertAddressIsValid( buffer, “\pDoSomething”);
 AssertUPPIsValid( callback, “\pDoSomething”);
 AssertFileRefNumIsValid( fileRefNum, “\pDoSomething”);

    ... useful code goes here ...

 err  = SomethingElse();

 AssertNoErr( err, “\pDoSomething”);
 return( err );
 }

Consistent use of the above technique with every routine you write will provide major benefits, especially on team projects, where not everyone is familiar with the code. Even if it’s only yourself, you will be grateful for the notification when you call it incorrectly one day. In some cases, when you review your code, the asserts are the only clue you’ll have as to the proper value of the parameters. In such cases, they can save you much time and aggravation when trying to determine what the programmer intended. They also demonstrate whether the programmer thought about what requirements the routine had when writing it. When asserts are missing, it is often unclear what requirements are present unless you carefully read through the code-an onerous task in some cases. Those familiar with the theoretical aspects of program correctness will recognize that a prerequisite of proving code correct is establishing its calling requirements. Asserts document those requirements.

It should be noted that within a routine, certain areas of the code may have their own assumptions and requirements. These are good places to add asserts which document those conditions at that point in the code.

Note that although asserts do increase source-code size, they often can take the place of comments which invariably become inaccurate as the code is modified. They are “smart comments” because they make explicit the requirements, and guarantee the requirements are met when the routine is called. Such an approach is vastly superior to a comment that says “must not be nil” because an Assert is actually enforced at runtime (at least in the DEBUG version). Forget those types of comments and use Asserts instead.

Debugging “Traps”

We’ve now discussed creating and using asserts. This next section discusses how to create debugging versions of system calls using asserts and other techniques.

For many years I’ve wished that Apple would provide a debugging version of the ROM. Years went by before I thought of the following approach which effectively lets you write debugging versions of system calls such as NewHandle. There have been various tools that have made such checking possible, but they all have limitations of various sorts. Use of the following technique requires no change to your source code and can readily be applied to older source code bases. It could also be applied to non-system routines or other library routines.

The technique is simple: use the C/C++ macro preprocessor to substitute your own debugging version of a call for the system one. Your version makes appropriate debugging checks, calls the real routine, and if appropriate, checks the results of the call. With such an approach you can verify the validity of parameters and flag any error conditions that result from the call. Your checks can be very stringent. For example, suppose you want to exercise debugging code whenever DisposeHandle() is called. Symantec’s implementation performs the following checks:

• verifies that the Handle is valid;

• verifies that it is not a resource;

• sets all bytes of the Handle to a garbage value;

• verifies that no error occurred.

 pascal void
DebugTraps_DisposeHandle(Handle h)
 {
 UInt32 hSize;
 SInt8  hState;
 
 AssertHandleIsValid( h, “\pDebugTraps_DisposeHandle”);
 
 hState = HGetState( h );
 Assert( ! HStateIsResource( hState ),
 “\pDebugTraps_DisposeHandle: This Handle is a resource.
  Use ReleaseResource instead”);
 
    // fill the handle with garbage prior to disposing it
 hSize  = GetHandleSize( h );
 if ( MemError() == noErr )
 {
    // note: FillWithGarbage doesn’t move memory so
    // Handle doesn’t need to be locked
 FillWithGarbage( *h, hSize); 
 }
 
 DisposeHandle( h );

    // use LMGetMemErr instead of MemError so
    // error code doesn’t get cleared
 AssertNoErr( LMGetMemErr(),
 “\pDebugTraps_DisposeHandle”);
 }

Setting the contents of the Handle to garbage values has the major benefit of flushing out other bugs. Any other code that retains a reference to a disposed Handle should crash or start acting strange soon thereafter, rather than much later. Whacking the Handle contents also tends to fill memory with values that cause bus errors. This can flush out errors that otherwise might go undetected. Enormous amounts of time can be saved by such error detection. And if the bug gets into a shipping product, producing a revision to fix the problem can be very expensive.

Any system calls that allocate, dispose or otherwise manipulate memory are particularly appropriate for this kind of debugging code (e.g. NewPtr, DisposePtr, NewHandle, DisposeHandle, etc). Symantec’s implementation of “debugging traps” now covers several hundred toolbox and operating system calls. While this may seem like a lot of work, the potential savings across multiple teams and multiple projects is huge. It is not uncommon for a programmer to spend a day or two tracking down an obscure crash that could easily be detected by a debugging trap. If you spend the time writing debugging traps just once, you’ll get a steady dividend of increased productivity.

Note that use of debugging traps requires no source code changes; you continue to write:

 DisposeHandle( theHandle );

You do not need to write:

 DebugTraps_DisposeHandle( theHandle );

Instead, the C/C++ macro preprocessor takes care of substituting the call to DebugTraps_DisposeHandle instead of a direct call to DisposeHandle.

The elegance of this technique is that no changes are required to your source code, yet you have stringent debugging turned on for your code and the code that everyone else on your team writes! In fact, team members don’t even have to know this technique is being used (except when it detects an error). The benefit of this, especially for legacy code, is enormous, because you get instant bug notification for any code which you compile. And when DEBUG is off, you pay no penalty whatsoever for this benefit.

Implementing a debugging traps scheme

To implement a debugging traps facility, you will need to do the following:

1. create source file(s) to contain the debugging traps, say “DebugTraps.c”.

2. create a header file which contains macro definitions for the traps and function prototypes for the debugging calls (“DebugTraps.h”). When DEBUG is on, the macros redefine trap calls to vector to the debugging versions; when DEBUG is off, nothing is redefined and the code compiles normally. For example:

#if DEBUG
 #define BlockMove DebugTraps_BlockMove

 pascal voidDebugTraps_BlockMove(const void *srcPtr,
 void *destPtr, Size byteCount);
#endif

3. create an “off” file (“DebugTrapsOff.h”). This file #undefs all debugging traps. Such a file is used in a very few places (such as DebugTraps.c) so that the real trap may be called without recursion problems:

 #undef BlockMove

4. #include “DebugTraps.h” in any source files in which you want debugging traps. We include it in our project prefix so that all source files are subject to debugging traps. Obviously, the value is much greater to have it on for all files, rather than for just a few.

As you encounter new bugs having to do with making inappropriate system calls, take the time to add that knowledge to a debugging trap for that call. It will pay off handsomely, since you will never again make the same mistake-the debugging trap will notify you as soon as it happens! For example, a common mistake is to call DisposeHandle on a resource. There is no reason to ever make this mistake if you have a debugging version of DisposeHandle which flags an attempt to dispose a resource Handle.

When writing a debugging trap, it makes sense to place very stringent asserts on parameters of these debugging calls. Don’t skimp; assert every single parameter as stringently as possible. Check for errors and flag any possible situation that could lead to a problem. Assume the client will pass bad parameters and will not check for errors, and flag those situations!

The most productive debugging traps are those that allocate, dispose, or otherwise manipulate memory or resources. The sample code included with this article contains debugging traps for memory. When you start to use it, consider implementing adding all resource manager calls right away.

Detecting memory leaks

We’ve now discussed how to write “debugging traps”. This last section discusses how to detect memory leaks using the debugging traps facility. Detecting memory leaks is by far the most complicated technique to implement (but not to use). Only an overview can be given due to space considerations.

A common programming error is failure to release memory that is no longer used. Yet it is straightforward to eliminate this type of error forever, with almost no impact on your source code and no ongoing programming effort, even for new projects.

The leaks checking (“Leaks”) module we use at Symantec requires the debugging traps facility discussed in this document. The approach is simple: all routines that allocate memory notify Leaks of the type, size and nature of the allocation. All routines that deallocate memory notify Leaks that the memory has been disposed. With debugging traps, this is trivial to implement: simply include calls to the Leaks code for memory that is allocated or deallocated. This includes routines such as NewHandle, NewPtr, and even routines such as NewWindow, NewIconSuite, NewRgn, etc. Corresponding disposal routines notify the Leaks manager when memory is disposed. Obviously, to track all possible types of leaks, you must write a debugging trap for any routine that allocates or disposes memory so that it can call the Leaks manager. Such routines include NewWindow, NewIconSuite, NewRgn, etc. C++ objects, though not handled in a debugging trap, are handled in a similar fashion: operator new() and operator delete() are replaced with versions that call the normal version, but also make calls to the Leaks manager. Other types of memory allocation could be handled in a similar manner.

In addition to tracking whether memory is disposed, the Leaks manager verifies that it is being disposed of correctly. For example, you should not allocate a region with NewRgn and then dispose of it with DisposeHandle; instead you should call DisposeRgn.

Finally because Leaks code is debug code, it too disappears when DEBUG is off.

What the Leaks Manager does

The Leaks manager tracks memory allocation using a table of entries with one entry in the table for each allocated item. A table entry includes the following information for each allocated item:

• the size of the item;

• the kind (Handle, Ptr, object, etc);

• the call used to allocate the item (NewHandle, NewPtr, operator new, etc)

• a stack crawl;

• the name of the file containing the routine which allocated the memory

In addition, the Leaks manager maintains various other information, including statistics about how much memory of what kinds was allocated.

To use the leaks code, you first initialize it when you program starts up:

 DebugLeaks_Init();

You then initiate a named “session”; all further memory allocations are remembered for this session:

 DebugLeaks_StartSession( 1000, “\pmain”);

To see if leaks have occurred, you stop the session. This reports all leaks that have occurred and disposes of the session:

 DebugLeaks_StopSession( );

Here is how you would leak-proof your entire application:

 void
 main(void)
 {
 InitMac(); 
    // initialize toolbox, etc

 DebugLeaks_Init();
 DebugLeaks_StartSession( 1000, “\pmain”);

    ... initialize and run your program ...

 DebugLeaks_StopSession( );
 }

In Symantec’s implementation, sessions may be nested; this feature is useful for localizing problems without having to modify code elsewhere. For nested sessions, the Leaks manager simply keeps a stack of sessions. Memory allocations are remembered in the current session; memory disposal checks each session in turn to find the item being disposed.

When you stop a session, the Leaks manager reports the total number of leaks, and reports information about each individual leak, including a stack crawl for the leak. This makes it straightforward in most cases to immediately determine where the offending item was allocated. (It may be harder to determine why it was not deallocated!).

Of course, there are always a few wrinkles. Sometimes you allocate items you know you will never dispose (say certain global data structures or objects). In this case, you don’t want Leaks to report a leak. In such a case, you tell Leaks that the item is not a leak by calling DebugLeaks_IgnoreItem immediately after allocating the item.

A slightly more annoying problem is that programming frameworks permanently allocate items which they never dispose. To work around this, the routines DebugLeaks_SuspendSession and DebugLeaks_ResumeSession can be used to temporarily disable leaks tracking while the programming framework is initialized. In a few cases, you may have to take other steps so that the Leaks manager doesn’t consider such allocations to be leaks. Although this requires a little work, it is straightforward. In some cases, Leaks can check the supplied source file name and ignore memory allocations from those files. In the future, I would like to see programming framework vendors provide proper disposal routines for their frameworks so that before program termination all memory can be disposed of properly.

Leaks API

The API to our leaks manager consists of a variety of routines, almost all of which are called exclusively from the debugging traps code to remember or forget a memory allocation. Just skim past these routines now, and refer to them later as needed. Also, refer to the source code templates for comments on what each routine should do.

void    DebugLeaks_Init( void );
void    DebugLeaks_Dispose( void );

void    DebugLeaks_StartSession( ulong maxItemsToTrack,
 ConstStringPtr sessionName);
void    DebugLeaks_StopSession( void );

void    DebugLeaks_SuspendSession( void );
void    DebugLeaks_ResumeSession( void );
void    DebugLeaks_AssertNotSuspended(void);

void    DebugLeaks_RememberHandle( Handle theHandle,
 DebugLeaksHowAllocated how,
 const char *srcFileName);
void    DebugLeaks_ForgetHandle( Handle theHandle );

void    DebugLeaks_RememberPtr( void *thePtr,
 DebugLeaksHowAllocated how,
 const char *srcFileName);
void    DebugLeaks_ForgetPtr( void *thePtr );

void    DebugLeaks_RememberAEDesc( AEDesc *theAEDesc,
 DebugLeaksHowAllocated how,
 const char *srcFileName);
void    DebugLeaks_ForgetAEDesc( AEDesc *theAEDesc );

void    DebugLeaks_RememberObject( void *object,
 ulong size);
void    DebugLeaks_ForgetObject( void *object );

Boolean DebugLeaks_ItemIsRemembered( const void *item );

void    DebugLeaks_RefreshStackInfo( void *handleOrPtr );

void    DebugLeaks_DisposingHandle( Handle h );
void    DebugLeaks_DisposingPtr( Ptr p );

void    DebugLeaks_IgnoreItem( const void *item);

Suggestions For Implementing a Leaks Manager

The major housekeeping task of a leaks manager is maintaining a list of allocated items efficiently. In our implementation, when a session is started, you specify the maximum number of items that can be remembered in your call to DebugLeaks_StartSession. Memory is allocated at that time and released when the session is stopped. By allocating a fixed amount of memory per session, performance remains very high and the code stays simpler. If Leaks runs out of space to remember items, it complains. You then simply specify a higher limit, recompile, and try again (remember, this is debugging code). An improvement would be to have Leaks reallocate dynamically. In practice, this hasn’t been necessary.

The other issue is that of tracking items in the list. Our approach has been to maintain a compact array of structs that contain information about allocated items. New items are added to the end of the list. When an item is removed, the last item in the list is put in its place. In this manner, the list stays compact and empty entries begin after the last in-use entry. For example, you could have a table of 1000 entries. If there are 232 items being tracked, then items [0,231] are in use and items [232, 999] are empty and available for use.

Searching the list is a simple array traversal and determining the number of items in it is trivial. Technically speaking, adding an item takes O( 1 ), and removing an item takes O( n ), where n is the total number of remembered items in all sessions. However, removed items typically are ones that were recently added, so they can usually be found right away, so finding items to remove is usually extremely fast. In any case such traversal is usually considerably faster than the original call to dispose of the item (such as DisposeHandle) and in our experience, has little effect on program speed. Speed of debugging code should not be an issue as long as it is reasonable. Sorting the list was considered, but is actually far less efficient than just using an unordered list.

Leaks checking is most useful when adequate information is provided to track down the source of the leak. Useful information includes a stack crawl, the type of item (object, Handle, Ptr), the size of the item, the routine which allocated the item (NewHandle, etc), the file containing the routine which allocated the item, etc. All of this information can be stored in a small amount of space and made available when a leak is detected.

The type, size and routine which allocated the item are all known at the time the item is allocated (see the routine DebugTraps_NewHandle in DebugTraps.c for an example). The file containing the allocating routine can be determined using the __FILE__ preprocessor variable. __FILE__ generates a null terminated C string which contains the name of the source file currently being compiled.

The stack crawl can be determined by traversing return addresses on 68K machines and link registers on PowerPC machines (on both machines, turning Macsbug symbols on allows you to display routine names, instead of raw addresses). To generate stack crawls you’ll need to parse through the stack. On 68K machines, you’ll want to make sure the generated code uses A6 stack frames with Macsbug symbols turned on. In PowerPC code, you’ll need to turn on the “traceback” feature. Stack crawls are the most difficult piece of information to obtain. You may want to omit this information is you are not adept at assembly language or are unfamiliar with the details of how the stack works on 68K and PPC machines.

Finally, all of this information can be written to a log file, for later analysis. You can implement as little or as much of this as you find necessary; more is usually better because it makes it easier to track down the leak.

Leaks code can also be used to track the number, kind, and frequency of memory allocation. This information could be used to tune your program for better performance.

One note about storing file names: it is much more space-efficient to reference a string in an in-memory string list than to maintain a copy of the filename for each allocated item. For example, 10 Handles could be allocated in file “MyFile.c”. To save space, store the string “MyFile.c” in a string list, and refer to it by index. In other words, don’t store the entire string “MyFile.c” in every allocated item. Since you have only a limited number of source files, your list of file names will never get very large. This approach will drastically reduce space requirements.

To keep track of which routine allocated the item, you’ll want to use an enum containing values for each routine that allocates items. In the debugging trap, you’ll pass this enum value to the leaks manager. For example, in DebugTraps_NewHandle, you’d make the following call to the Leaks manager:

 DebugLeaks_RememberHandle( h,
 kLeaks_NewHandle, srcFileName);

Your Leaks manager should also be robust enough to detect attempts to remember the same item more than once or to forget it more than once. Attempts to do so are probably bugs in your program and should be flagged.

Prevention

It is better to prevent bugs in the first place than to detect them later. Use modern programming techniques that reduce the chances of bugs. Discussion of such techniques is beyond the scope of this article. However, there are a number of good books that discuss these types of issues. Here are several recommended books by authors who have their heads on straight regarding good design and coding practices:

1. Code Complete by Steve McConnell, Microsoft Press 1993, ISBN 1-55615-484-4. See http://www.microsoft.com/mspress/books/des/5-484-4a.htm (yes, the ‘l’ is missing).

2. 50 Effective Techniques For C++ by Scott Meyers, Addison-Wesley Professional Computing Series ISBN 0-201-56364-9. See http://www.aw.com/cp/meyers-effective.html.

3. Design Patterns by by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, Addison-Wesley Professional Computing Series 0-201-63361-2. See http://www.aw.com/cp/Gamma.html.

Conclusion

The techniques discussed in this article will detect many unnecessary and mundane bugs. As they say in Hollywood, “don’t call us, we’ll call you”. In this case, that’s a Good Thing! Let your bugs notify you when they occur and spend your energy elsewhere.

In our experience at Symantec, use of these techniques has contributed directly to faster and higher quality development. Time that formerly would have been wasted tracking down hard-to-reproduce problems can now be spent productively. Problems that went unnoticed in the past are now noticed-before shipping the product. All developers will benefit from the application of the techniques discussed in this article.

All of the techniques discussed in this article can be implemented by a good programmer in about a week. Make that effort just once and you’ll benefit far into the future.

about the Sample Code

The sample code is provided with a Metrowerks CodeWarrior 9 project. The code has not been compiled with other environments but it should compile with little or no modification in other environments. The code does not require C++, but should compile fine under a C++ compiler.

Please note that when you run the sample project you will drop into the debugger. The intention is to demonstrate how certain asserts work. Make sure you have Macsbug installed!

Refer to the sample code (available at http://www.mactech.com/ - ed/wgi) for more details on implementation of debugging traps and leaks checking. You should be able to use the debug traps facilility provided in the sample code immediately in all your projects with no modification. The Leaks manager portion is not implemented although the stub routines are called by the debug traps code. It should be fairly straightforward to implement the Leaks code to provide basic functionality. Data structures are suggested in DebugLeaks.c.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Dropbox 193.4.5594 - Cloud backup and sy...
Dropbox is a file hosting service that provides cloud storage, file synchronization, personal cloud, and client software. It is a modern workspace that allows you to get to all of your files, manage... Read more
Google Chrome 122.0.6261.57 - 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
Skype 8.113.0.210 - Voice-over-internet...
Skype is a telecommunications app that provides HD video calls, instant messaging, calling to any phone number or landline, and Skype for Business for productive cooperation on the projects. This... Read more
Tor Browser 13.0.10 - Anonymize Web brow...
Using Tor Browser you can protect yourself against tracking, surveillance, and censorship. Tor was originally designed, implemented, and deployed as a third-generation onion-routing project of the U.... Read more
Deeper 3.0.4 - Enable hidden features in...
Deeper is a personalization utility for macOS which allows you to enable and disable the hidden functions of the Finder, Dock, QuickTime, Safari, iTunes, login window, Spotlight, and many of Apple's... Read more
OnyX 4.5.5 - Maintenance and optimizatio...
OnyX is a multifunction utility that you can use to verify the startup disk and the structure of its system files, to run miscellaneous maintenance and cleaning tasks, to configure parameters in the... Read more
Hopper Disassembler 5.14.1 - Binary disa...
Hopper Disassembler is a binary disassembler, decompiler, and debugger for 32- and 64-bit executables. It will let you disassemble any binary you want, and provide you all the information about its... Read more

Latest Forum Discussions

See All

Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »
Live, Playdate, Live! – The TouchArcade...
In this week’s episode of The TouchArcade Show we kick things off by talking about all the games I splurged on during the recent Playdate Catalog one-year anniversary sale, including the new Lucas Pope jam Mars After Midnight. We haven’t played any... | Read more »
TouchArcade Game of the Week: ‘Vroomies’
So here’s a thing: Vroomies from developer Alex Taber aka Unordered Games is the Game of the Week! Except… Vroomies came out an entire month ago. It wasn’t on my radar until this week, which is why I included it in our weekly new games round-up, but... | Read more »
SwitchArcade Round-Up: ‘MLB The Show 24’...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for March 15th, 2024. We’re closing out the week with a bunch of new games, with Sony’s baseball franchise MLB The Show up to bat yet again. There are several other interesting games to... | Read more »
Steam Deck Weekly: WWE 2K24 and Summerho...
Welcome to this week’s edition of the Steam Deck Weekly. The busy season has begun with games we’ve been looking forward to playing including Dragon’s Dogma 2, Horizon Forbidden West Complete Edition, and also console exclusives like Rise of the... | Read more »
Steam Spring Sale 2024 – The 10 Best Ste...
The Steam Spring Sale 2024 began last night, and while it isn’t as big of a deal as say the Steam Winter Sale, you may as well take advantage of it to save money on some games you were planning to buy. I obviously recommend checking out your own... | Read more »
New ‘SaGa Emerald Beyond’ Gameplay Showc...
Last month, Square Enix posted a Let’s Play video featuring SaGa Localization Director Neil Broadley who showcased the worlds, companions, and more from the upcoming and highly-anticipated RPG SaGa Emerald Beyond. | Read more »
Choose Your Side in the Latest ‘Marvel S...
Last month, Marvel Snap (Free) held its very first “imbalance" event in honor of Valentine’s Day. For a limited time, certain well-known couples were given special boosts when conditions were right. It must have gone over well, because we’ve got a... | Read more »
Warframe welcomes the arrival of a new s...
As a Warframe player one of the best things about it launching on iOS, despite it being arguably the best way to play the game if you have a controller, is that I can now be paid to talk about it. To whit, we are gearing up to receive the first... | Read more »
Apple Arcade Weekly Round-Up: Updates an...
Following the new releases earlier in the month and April 2024’s games being revealed by Apple, this week has seen some notable game updates and events go live for Apple Arcade. What The Golf? has an April Fool’s Day celebration event going live “... | Read more »

Price Scanner via MacPrices.net

Apple Education is offering $100 discounts on...
If you’re a student, teacher, or staff member at any educational institution, you can use your .edu email address when ordering at Apple Education to take $100 off the price of a new M3 MacBook Air.... Read more
Apple Watch Ultra 2 with Blood Oxygen feature...
Best Buy is offering Apple Watch Ultra 2 models for $50 off MSRP on their online store this week. Sale prices available for online orders only, in-store prices may vary. Order online, and choose... Read more
New promo at Sams Club: Apple HomePods for $2...
Sams Club has Apple HomePods on sale for $259 through March 31, 2024. Their price is $40 off Apple’s MSRP, and both Space Gray and White colors are available. Sale price is for online orders only, in... Read more
Get Apple’s 2nd generation Apple Pencil for $...
Apple’s Pencil (2nd generation) works with the 12″ iPad Pro (3rd, 4th, 5th, and 6th generation), 11″ iPad Pro (1st, 2nd, 3rd, and 4th generation), iPad Air (4th and 5th generation), and iPad mini (... Read more
10th generation Apple iPads on sale for $100...
Best Buy has Apple’s 10th-generation WiFi iPads back on sale for $100 off MSRP on their online store, starting at only $349. With the discount, Best Buy’s prices are the lowest currently available... Read more
iPad Airs on sale again starting at $449 on B...
Best Buy has 10.9″ M1 WiFi iPad Airs on record-low sale prices again for $150 off Apple’s MSRP, starting at $449. Sale prices for online orders only, in-store price may vary. Order online, and choose... Read more
Best Buy is blowing out clearance 13-inch M1...
Best Buy is blowing out clearance Apple 13″ M1 MacBook Airs this weekend for only $649.99, or $350 off Apple’s original MSRP. Sale prices for online orders only, in-store prices may vary. Order... Read more
Low price alert! You can now get a 13-inch M1...
Walmart has, for the first time, begun offering new Apple MacBooks for sale on their online store, albeit clearance previous-generation models. They now have the 13″ M1 MacBook Air (8GB RAM, 256GB... Read more
Best Apple MacBook deal this weekend: Get the...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New 15-inch M3 MacBook Air (Midnight) on sale...
Amazon has the new 15″ M3 MacBook Air (8GB RAM/256GB SSD/Midnight) in stock and on sale today for $1249.99 including free shipping. Their price is $50 off MSRP, and it’s the lowest price currently... Read more

Jobs Board

Early Preschool Teacher - Glenda Drive/ *Appl...
Early Preschool Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter Read more
Senior Software Engineer - *Apple* Fundamen...
…center of Microsoft's efforts to empower our users to do more. The Apple Fundamentals team focused on defining and improving the end-to-end developer experience in Read more
Relationship Banker *Apple* Valley Main - W...
…Alcohol Policy to learn more. **Company:** WELLS FARGO BANK **Req Number:** R-350696 **Updated:** Mon Mar 11 00:00:00 UTC 2024 **Location:** APPLE VALLEY,California Read more
Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill WellSpan Medical Group, York, PA | Nursing | Nursing Support | FTE: 1 | Regular | Tracking Code: 200555 Apply Now Read more
Early Preschool Teacher - Glenda Drive/ *Appl...
Early Preschool Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.