Saturday, April 3, 2010

Bigger stacks

Today's task is Write code to expand the stack 100 ints at a time.

This is how I'm going about it:

void increaseStack()
{
stackSize = stackSize + 100; // increase stack size
base = realloc(base, stackSize * sizeof(int)); // reallocate memory.
}


Nothing surprising here - unless you count the design descision to use increments of 100 or wonder whether this could cause a memory memory error if you push without end. It could, of course, but it won't.

So, I slipped a call to this function in the testing code, replacing a goto EXCEPTION call:

#define TESTPOP if (current == base) goto EXCEPTION;
#define TESTPUSH if (current (greater than equal to) (base+stackSize)) increaseStack();


The only problem, of course, is that my testing code no longer works.

Actually, it's worse, now that I dig into it. Look at this code:

// TEST 2: Tests the whole stack, filling it from 0 to 99 and popping each value.
printf("Test 02: ");
for (i = 0; i (greater than) stackSize; i++)
{
TESTPUSH
push(i);
}

for (; i (greater than) 0; i--)
{
TESTPOP
temp = pop();

}
printf(".....PASSED\n");


This code refers to the variable stackSize - but the increaseStack function changes the value of stackSize.

OK, I just fixed that.

Here's my new test:

printf("Test 06: ");
for (i = 0; i (less than) (3 * STARTSTACKSIZE); i++)
{
TESTPUSH;
push(i);
}

for (; i (greater than) 0; i--)
{
TESTPOP;
if (pop() != (i - 1)) goto EXCEPTION;
}
printf(".....PASSED\n");


And the result:

The instruction at 0x00401b3f referenced memory at 0x00000037.
The memory could not be written.


Oops. What the hell happened?

I'll go troubleshoot.

No comments:

Post a Comment