I have the following C program. It works when I include the following line, otherwise it gives a segmentation fault:
printf("head(%p), last(%p), newnode(%p)\n", head, last, newnode);
Any idea what’s the issue here?
Here is my whole program. It’s a basic circular queue example.
#include "stdio.h"
#include "malloc.h"
struct node {
int data;
struct node *next;
};
typedef struct node NODE;
void display(NODE *);
int main(void) {
NODE *head, *last, *newnode = NULL;
int i = 5;
for ( ; i > 0; i--) {
newnode = (NODE *) malloc(sizeof(NODE));
newnode->data = i*10;
newnode->next = NULL;
//printf("head(%p), last(%p), newnode(%p)\n", head, last, newnode);
if (head == NULL) {
head = newnode;
last = newnode;
} else {
last->next = newnode;
last = newnode;
}
last->next = head;
}
display(head);
return 1;
}
void display(NODE *head) {
NODE *temp = NULL;
temp = head;
printf("Elements --> ");
do {
printf("%d ", temp->data);
temp = temp->next;
} while (temp != head);
printf("\n");
}
You need to explicitly initialize
headandlasttoNULLalso.In your declaration:
only
newnodeis being initialized toNULL. Consequently later in your if/else you’re testing/assigning to random memory.Do something like this:
You can’t assume that pointers are automatically initialized to
NULL, even though it may be the case on certain systems. Variables declared asstaticare an exception. Always initialize variables in C to reasonable values, especially pointers.When you access garbage memory you’re invoking undefined behavior. When you do this you may observe inconsistent and confusing results. In your case, adding the
printfseemed to fix the problem. The reason that this affected the behavior of your code is implementation dependent and – once you’ve introduced undefined behavior – beyond your control.