> From: Brian Smith
>
> So, does this mean that it's *optional* to use MemPtrNew? If so, then I'm
> really confused! If you don't *have* to use it, why would you?
>
As I understand it, you should use MemPtrNew or MemHandleNew to dynamically
allocate memory when you want to avoid using up stack space, which is very
limited, or when you won't know how much memory you need until the program
is running. Whether to use MemPtrNew or MemHandleNew depends on how long
you want the memory to be available. For short durations, such as during
the lifetime of a single function, you can use either and so most people use
MemPtrNew since it is simpler. For longer durations, you should use
MemHandleNew, then lock it to get a pointer when you need to use the memory
and unlock as soon as possible. That way, the OS can move the memory block
if it needs to do so to allocate other memory.
Here are some examples (not exhaustive) of memory allocation:
1. In a global at the start of your main.c (or whatever) -
Char myString[20];
This allocates 20 bytes for the string which will exist for the duration of
your program.
2. In a global at the start of your main.c (or whatever) -
Char * myString;
This allocates 2 (or 4?) bytes for a pointer to some Chars which haven't
been allocated yet. Then, to get memory for the string, you would call
MemPtrNew or MemHandleNew. One advantage here is that you can allocate 20
bytes or more or less as needed.
3. Inside a function -
Char myString[20];
This allocates 20 bytes for the string on the stack which will exist for the
life of the function.
4, Inside a function -
Char * myString;
This allocates 2 (or 4?) bytes for the myString pointer on the stack. Then,
to get memory for the string, you would call MemPtrNew or MemHandleNew,
which allocate memory from the dynamic heap that will last until you free
it. One advantage (or disadvantage, depending on how you look at it) with
this is that you can allocate memory in one function that is used by another
function (but then you have to be careful to clean up the memory!)
--
For information on using the Palm Developer Forums, or to unsubscribe, please see
http://www.palmos.com/dev/tech/support/forums/