Sunday, April 4, 2010

Assuming assumptions

So, after playing around with my code yesterday, I realized that my mistake was forgetting the fundamental design of my stack.

I used two variables for the stack, base and current. Both of these were pointers to memory. Base never changed, but current changes with pushes and pops. The last time I did a stack - in ARM Assembly - I simply had a pointer and incremented and decremented it.

The problem was that when I redid the program to use realloc, I reset base, but left current alone.

This is worse than simply a mistake, since it wouldn't always break things. After all, realloc doesn't _have_ to move anything. If there's space for the new memory, realloc simply leaves things where they are.

It was a screw up, but it gave me a chance to add an assert statement to my build for testing. I wasn't sure whether the execution was getting to some code. I usually use printf statements to verify that part of the code was reached, but that is not valid. A memory error can break the program before everything in the output queue has time to print.

I used an assert(0 == 1) to stop the code at a certain point or in certain circumstances.

A better approach is to not make mistakes to begin with, but maybe that's too high a bar.

No comments:

Post a Comment