Tuesday, February 17, 2009

leaves and traps..... (II)

How to work with leaves

We assume that a function has previously allocated memory on the heap and this memory is pointed to by a local pointer variable. Now,if a leave occurs within that function then ,that pointer will be destroyed by the Leave (As Leave unwinds the stack frame upto the TRAP macro). Lets see,


Eventually the memory pointed to by "test" variable is unallocated and will result in a memory leak.
How to prevent this?

If we have to use any local variable which point to heap objects, we must push the variable to the CleanupStack before calling any function that may leave.

Important Note:
1. Member variables are leave-safe
2.Neither a constructor nor a destructor should contain code that may
leave, since doing so would potentially leak memory.

Leaves Vs Panics

1. Leaves occur in exceptional conditions (Out of memory or Out of disk conditions). Leaves should be handled properly to continue the normal flow of execution. Leaves do not terminate the normal flow of execution. On the other hand, Panics cannot be caught and handled.

2. Leaves occur at program runtime due to exception situation. Panics , on the other hand occur at the development time. If they occur at runtime, they cannot be fixed. So, the cause pf panics should be searched and fixed at development period.

0 comments: