free Function

If we discover that the stack is not empty as it should be at the end of the computation, we must clean it up by popping off any items that are still on it. We do this with a while loop, and our, as yet undefined, popItem function. This clean up is important, otherwise we will begin to fill up memory with unused junk. This sort of garbage collection is imperative in programs that dynamically allocate space for data as ours does.

Here is a simple popItem function which simply frees the space used by the item on top of the stack and returns a pointer to the next item down, which can then be made the new stack top:

node * popItem(node * stackTop)
    static node * temp;
    temp = stackTop->nextnode;
    return temp;

Here we have used the free function from the stdlib library to free the space taken up by the node we are popping. This function tells the operating system that this piece of memory is now no longer required and can be reused by this or another program. It has no return value. Many programs crash simply because a programmer forgot to free memory no longer used. This is called a memory leak and should be avoided at all costs.

When the bottom item on the stack was created, it was completely set to zero by the calloc function. In particular this automatically set the pointer nextnode equal to NULL. This never changes for the bottom item on the stack and so if we try to pop the final item on the stack, the return value of popItem is set to a NULL pointer by the above code. This is precisely what we want to happen, since stackTop is then set equal to this NULL pointer upon return of popItem, correctly indicating that the stack is now empty.

Finally we implement the default case by outputting an error with printf and cleaning up the stack as for the carriage return case.

Remarkably this is all we need to do for our Polish postfix calculator. Below is a C source file containing the full program as we have described it above. You can download this file and compile it in Pelles C (or any fairly standard C compiler) and modify it in various ways to see how it behaves.

Calculator Program (calculator.c)