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.