Sunday, April 18, 2010

Everybody out of the pool

The thing that I've found about learning C is that many of the things that seem arbitrary when learning high-level languages - like C# or java - make perfect sense when you see what's living beneath them. My favorite example is the switch statement. Type casting make more sense when you see how C or assembly language deals with it.

Last week, I was thinking of string pools. More talk later - here are my first steps in implementing a string pool. (This is all C, but C++ might be easier.)

First up, we need a string. In C, the first thing I kind of understood was that strings are sequences of characters - identified as the char pointer to the first member and closed with a delimiter character - some kind of end of line character.

That's picked up, partly, in a string pool approach by creating a structure that includes the pointer:

typedef struct {
char * base;
int length;
int sum;
} myString;


With a string represented as a struct, though, you can get rid of the delimiter and just specify the length of the string.

In Java, Strings are invariant. Once you create one, it can't be changed. When it was created, it lived in "the string pool" until you weren't using it any longer.

Of course, you could always create a new string, assign it to the old variable, and you're off to the races. The string pool seemed pointless to me. A giant happy world of "Why bother?"

But if you want to read a string in C, you have to look at every character you read to see if it's the delimiter. With a struct approach, you can just read as many characters as are defined in the struct. Here's how my preliminary program prints out a string:

void printMyString(myString x)
{
for (i = 0; i (less than) x.length; i++)
{
c = *(x.base + i);
printf("%c", c);
}
printf("\n");
}


No compares. It just reads the right number of characters.

So, invariant strings make sense. If you change a string in place, you also have to keep track of how it's length changes. (I haven't looked at what's under StringBuffer, the java thing that you can change. I might be able to guess, though, or implement something that works that way.)

As for a string pool, if the strings are going to be invariant, ans if you have some that might appear more than once - or even often - you get a memory savings by reusing them. (I wonder if it's a big savings.)

Other stuff - it's easier to compare strings in this approach. If two stings have the same value for base, they must be the same. (Actually, this assertion rests on the string pool being managed so you don't have two string stucts pointing to the same base but with different lengths. A sub-string relationship.)

The opposite isn't true, though - if two string point to different memory locations, they aren't necessary different strings (they're just different tokens.) The length item, however, can also be compared. If two strings have different lengths, they are different.

I also made a stab at including a checksum in my string class. Here's the code creating one of these:

myString saveString(char * y)
{
myString x;

x.base = y; // pointer to start of string.
x.length = 0; // initialize length.
x.sum = 0; // initialize sum.

while (0==0)
{
c = fgetc(stdin); // get char from stream.

if (c == '\n') break; // exit loop at \n
* (x.base + x.length) = c; // Assign char to location.
x.length++; // increment length
x.sum = x.sum ^ c; // my quasi check sum. Uses XOR on each new C.

}

return x;
}


I understand a bit about checksums, hashes, and related technologies. I implemented as simple bitwise XOR. I don't know if this is valid - I suspect it's not, considering cases where two stings have the same characters and the same length, but different orders. I'm sure there are algorithms out there that could be swapped in for my sum calculation.

That's the bones of a real approach. I could go on and set up an area of memory as a pool and manage it in a way similar to the memory manager I set up for ARM assembly. Or, add a second *char value to the string that points to the next string and manage it as a linked list.

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.

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.

Tuesday, March 30, 2010

Suites for the suite

I took a little detour, tonight, from my list of tasks to tidy up a little.

I wrote some test code to verify that the push and pop are working pretty much as I expect. Here's the output:

Test 01: .....PASSED
Test 02: .....PASSED
Test 03: .....PASSED
Test 04: .....PASSED
Test 05: .....PASSED


Which doesn't mean anything unless you know what the tests are.

Test 01 verifies basic operation. It pushed 14 and pops once and verifies that the result is 14:

printf("Test 01: ");
TESTPUSH
temp = 14;
push(temp);
TESTPOP
if (pop() != temp) goto EXCEPTION;
printf(".....PASSED\n");


TESTPUSH, TESTPOP, and the if statement can each break it with the same result:

Test 01: Error: Exiting.

Test 02 pushes and pops 100 values:

printf("Test 02: ");
for (i = 0; i (less than) stackSize; i++)
{
TESTPUSH
push(i);
}

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

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

Test 03 verifies that the same value is pushed as popped. This is a little more specific than Test 02, which just cares about staying inside the stack range.

Test 04 and 05 just check whether the logic of the testing code works. These might be better at the start of the test section, but I'm not moving things around right now.

// TEST 4: Verifies the test code for pops by negating it.
printf("Test 04: ");
if (current != base) goto EXCEPTION;
printf(".....PASSED\n");

// TEST 5: Verifies the test code for pushes by negating it.

printf("Test 05: ");
for (i = 0; i (less than) stackSize; i++)
{
TESTPUSH;
push(i);
}
if (current != (base+stackSize)) goto EXCEPTION;
printf(".....PASSED\n");


Next, resizing the stack with realloc.

Monday, March 29, 2010

The New Number Two

So, tonight I did the second thing on my list of stack tasks:

Write code to deal with cases outside the expected cases.

Basically, I dealt with two situations:
  • More pops than pushes.
  • More than 100 pushes.
Both pieces of testing code work by checking current against base. If there is a problem, it jumps to the following alternative program exit:


EXCEPTION: printf("Error: Exiting.\n");

return 0;


This means that the state of the stack is tested BEFORE any changes are made. Later versions of this, instead of exiting, will modify the stack to allow for additional pushes.

Here's POP:

#define POP if (current == base) goto EXCEPTION; pop(); // deal with extra pop.

I used a compiler directive to tie the test with the pop.

Here's PUSH:

#define PUSH(x) if (current == (base+stackSize)) goto EXCEPTION; push(x);


Next: Expanding the stack.

Saturday, March 27, 2010

First task

Although I describe it as a queue in my list, the first few versions of this are a simple stack implemented in memory. Later versions will implement FIFO functionality.

Here's the stack:
base = malloc(arraySize * sizeof(int)); // Allocate memory for stack. NOTE: Memory is not freed.


"base" seems like a funny name for a stack pointer, but I expect to create a separate value for pointer and keep "base" for other stuff - like checking whether there have been more pops than pushes.

There's a push and a pop:

void push(int value)
{
*base = value; // Assign value to location.
base = base + 1; // Increase location one element.
}

int pop()
{
base = base - 1; // Decrease location to previous location
return *base; // Get value at current location
}

And I wrote various testing code, which lives in main(), such as the following:

for (i = 0; i (less than) 100; i++)
{
push(i);
}

This code (and some other I wrote) tests the program as it is intended to be used (no more pops than pushes and no pushes beyond the size of the stack.)

And here's some code that breaks it:


for (i = 0; i (less than) 1000000; i++)
{

push(i);
}


This got me a fun (and expected) "The memory could not be written." error.

The next version of the program will handle the edge cases - probably by throwing an exception if the stack tries to pop below 0 or push above 100.

I had so much fun with assembly . . .


Back in January, I started a blog called Learning ARM Assembly in 30 Days where I played with programming for ARM chips.

It was a lot of fun and I created a fun memory manager that I can only run in a simulator program.

But - as I explained in the blog - there was kind of a limit to how much I could accomplish for that platform. But there's some stuff I should have down a little better in real computer languages, like C, so I'm going to do that for a while.

Above is my first list of tasks. You'll notice that 1 is already crossed off. I'll describe it in the next post.