Wednesday, 25 September 2013

C Infinite Pointer Loop (Caused By Duplicate Value?)

C Infinite Pointer Loop (Caused By Duplicate Value?)

Compiling with MinGW with -O3 -Wall -c -fmessage-length=0 -std=c99
Well, this is what I think the problem is... Here's the breakdown:
I have a linked list that I built using
typedef struct Coordinate{
int x;
int y;
struct Coordinate *next;
} Coordinate;
I am adding "valid moves" (in the game Reversi/Othello) on a 6x6 board
(matrix). My logic for checking whether or not a move is valid or not
works just fine - it's adding things to the list that gets me into
trouble.
For obvious reasons I want to avoid adding duplicate values to the list.
However, every function I attempt to code (that seems like it should work)
just crashes the application, segfaulting all the live long day.
So here's a function that I attempted to code:
int inList(Coordinate *list, int x, int y) {
if (list == NULL) return 0;
while (list != NULL) {
if (list->x == x && list->y == y) return 1;
else list = list->next;
}
return 0;
}
and called it like:
Coordinate *validMoves = createNewCoordinate(-1, -1); // Just so that
there is *something*
if (!inList(validMoves, 1, 1)) {
validMoves->next = createNewCoordinate(1, 1);
validMoves = validMoves->next;
}
So as far as I know, this should work perfectly. I've looked up examples
online and all my really convoluted uses of pointers in this particular
program have worked without a hitch thus far.
Anyway, the real problem is that if I don't prevent duplicates from being
entered into the same list (connected through pointers), then I get an
infinite loop (I imagine this is caused by two elements being considered
equal because their non-pointer types are equal).
I've posted all three parts of the code on pastebin for full reference (no
worries, open source, man!): othello.c othello_engine.c othello_engine.h
I've tried debugging but I'm not very good at that, I didn't really see
anything worth mentioning. Can anyone explain what might be happening
and/or give an example of how to avoid duplicates in a linked list? (I've
tried so many ways my brain hurts)

No comments:

Post a Comment