I don't understand why the following code results in error unhandled exception:
enqueue 50
enqueue 100
dequeue all to rear = 100---
ok2
50
CRT: unhandled exception (main) -- terminating
*** Process returned 255 ***
The problem seems to be in the line if (q -> front == NULL) {, but if I remove the comment from the test message above that line, it works. This probably means that I'm doing an undefined behavior of sorts, but I really don't understand why. The code works fine in GCC, but I don't think there's something wrong in Pelle's, there must be something wrong with my code, I just can't figure it out.
Can anyone help ?
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
typedef struct test1 {
int index;
struct test1 *next;
} test1;
typedef struct {
test1 *front;
test1 *rear;
} test2;
test1 dequeue(test2 *q)
{
test1 dequeued = {-1, NULL};
if (q -> front != NULL) {
memcpy(&dequeued, q -> front, sizeof dequeued);
test1 *p = q -> front;
q -> front = q -> front -> next;
//puts("ok1");
if (q -> front == NULL) {
puts("ok2");
q -> rear = NULL;
}
free(p);
}
return dequeued;
}
void enqueue(test1 pr, test2 *q)
{
printf("enqueue %d\n", pr.index);
test1 *newnode = malloc(sizeof pr);
assert(newnode != NULL);
memcpy(newnode, &pr, sizeof pr);
newnode -> next = NULL;
if (q -> front == NULL) {
q -> front = newnode;
} else {
q -> rear -> next = newnode;
}
q -> rear = newnode;
}
int main()
{
test2 Q = {NULL};
test1 pr;
pr.index = 50;
enqueue(pr, &Q);
pr.index = 100;
enqueue(pr, &Q);
printf("dequeue all to rear = %d---\n", Q.rear -> index);
while (Q.front != NULL) {
pr = dequeue(&Q);
printf("%d\n", pr.index);
}
}