At 11:17 AM 4/10/99 -0500, you wrote:
>What's never been clear, (I can hear the seasoned pros sighing already), is
>when one must explicitly allocate memory and when an implicit allocation is
>fine.  For example:
>
>char sString[ MAX_STRING_LENGTH ];
>

In this case, the memory is allocated on the stack (assuming the
declaration is inside a function call).  This is not so good because stack
space is fairly limited under PalmOS, and it's best not to take it up where
it's not necessary.  

>vs.
>
>VoidHand hString = MemHandleNew( MAX_STRING_LENGTH );
>pString = MemHandleLock( hString );
>...do something with the string
>MemHandleUnlock( hString );
>MemHandleFree;
>

In this case, the memory is allocated from the dynamic heap.  This too is
limited, but less so.  Also, here you are giving the OS a chance to tell
you you're out of room, by returning NULL from MemHandleNew.

>Memory is obviously allocated in either case.  But which is the preferred
>method?  I see both methods in the example code.  Why would I choose one
>method over the other?  The latter example uses 4 lines of code, not
>including checking that the handle was allocated or declaring the pointer
>while the former uses 1 line.  And I'm assuming here that neither of these
>examples would leak, right?
>
Okay, in  order.  

>which is the preferred method?
I prefer to allocate the memory myself for the reasons mentioned.  

> Why would I choose one method over the other?
The first one is way easier to program, less prone to accidental leaking,
and is clearer in examples which are not trying to show how to allocate
memory.  The latter is more efficient in terms of stack space and gives the
OS more leeway in where the memory comes from, and what to do if it's not
there.  

>The latter example uses 4 lines of code, not including checking
>that the handle was allocated or declaring the pointer while the
>the former uses 1 line.

If you are only going to use the memory for a short stretch, you could save
yourself a lock and unlock call:

CharPtr pString = MemPtrNew (MAX_STRING_LENGTH)
if (NULL != pString)
{
   // .. do something with the string
   MemPtrFree (pString)
}

But, yes, the latter method requires more lines of code.

>And I'm assuming here that neither of these
>examples would leak, right?

As coded, there would be no leak.

Hope this helps.

Regards,
Greg

Greg Winton
Bachmann Software and Services, LLC
mailto:[EMAIL PROTECTED]
http://www.bachmannsoftware.com
Software Development for Handheld & Mobile Computing, Windows and the Internet
Home of Bachmann Print Manager, the only graphical printing solution for
the Palm Computing Platform

Reply via email to