Dan
Dan

Reputation: 3377

C: Seg fault is driving me insane

I've been debugging for a few hours and I really am completely lost. Help! NOTE: There is a lot more code than this in the program but the rest works fine so I tried to pull all relevant code. If you notice anything missing though, please let me know.

typedef struct cellT {
queueElementT value;
struct cellT *link;
} cellT;

struct queueCDT {
cellT *head;
cellT *tail;
};

void ReverseQueue(queueADT queue){
int i, x, length;
length = QueueLength(queue);
cellT *beg, *end;
queueElementT temp;

beg = queue->head;

for(i = 0; i < (length/2); i++){
    end = beg;
    for(x = 0; x < (length-i); x++)
        end = end->link;

    /* POINTERS REMAIN, VALUES SWAPPED */
    temp = beg->value;
    beg->value = end->value; /* gdb says issue happens here */
    end->value = temp;
}
}

Upvotes: 1

Views: 123

Answers (2)

alk
alk

Reputation: 70981

Just only swap if there is something to swap:

if (beg && end) {
  temp = beg->value;
  beg->value = end->value; 
  end->value = temp;
}

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409472

The problem might be this loop:

for(x = 0; x < (length-i); x++)

Try changing it to:

for(x = 0; x < (length-i) && end->link != NULL; x++)

Upvotes: 1

Related Questions