Im trying to create a Linked List in C but the program crashed due to some mysterious fault.
First I tried this:
typedef struct product_data product_data;
struct product_data {
int product_code;
int product_size;
product_data *next;
};
product_data *products_head = NULL;
product_data *products_tail = NULL;
int main() {
int newcode = 5;
int newsize = 5;
products_head->product_code = newcode;
products_head->product_size = newsize;
products_head->next = NULL;
return 0;
}
Unfortunately the program crashes without any error message.
Then I changed some parts:
typedef struct product_data product_data;
struct product_data {
int product_code;
int product_size;
product_data *next;
};
product_data *products_head = NULL;
product_data *products_tail = NULL;
int main() {
product_data *newproduct;
int newcode = 5;
int newsize = 5;
newproduct->product_code = newcode;
newproduct->product_size = newsize;
newproduct->next = NULL;
products_head = newproduct;
return 0;
}
No crash this time, it seems to work. I have no idea why though.
Any ideas?
Thanks in advance!
It doesn’t really work. You’re still dereferencing invalid pointers:
But while in the first version you were dereferencing pointers explicitly set to
NULL, it crashed with a segmentation fault like it should. Here you are dereferencing a pointer that contains whatever data lay on the stack, and unfortunately it doesn’t crash. It’s undefined behaviour, so it need not necessarily crash.You have to let your pointers point to valid memory,