I try to write a simple circular linked list programme for the purpose of practising C programming.
I create two structures. The first struct contain a struct of itself and a second struct. The seconds struct contain some information required during programme running.
Code:
struct c_list{
int id;
struct time_stamp *stamp;
struct c_list next;
};
struct time_stamp{
...
};
The problem I encounter is if I want to print the value stored in the stamp struct it would cause segment fault.
The way how I create nodes is to append the new node to the last node. the code snippet is as below:
Code:
struct c_list *node; // the last object in the list
struct c_list *tmp;
length++;
node = malloc(sizeof(struct c_list));
node->id = size();
node->stamp = data; // data is the struct of time_stamp
node->next = head;
if(head->next == head){
/* init state */
head->next = node;
}else{
/* has siblings */
tmp = head->next;
while(tmp->next != head){
tmp = tmp->next;
}
tmp->next = node;
}
The way how I print the list is
Code:
void
print_list(struct c_list *head)
{
struct c_list *node;
struct time_stamp *t;
node = head;
while(node){//not the last one
printf("node id: %d\n", node->id);
/* BEG
t = node->stamp;
printf("offset_from_master_seconds: %d\n", (t->offset_from_master).seconds);
printf("offset_from_master_nanoseconds: %d\n", (t->offset_from_master).nanoseconds);
printf("observed_drift: %d\n", t->observed_drift);
printf("sys_clock_seconds: %d\n", (t->current_sys_clock).seconds);
printf("sys_clock_nanoseconds: %d\n", (t->current_sys_clock).nanoseconds);
END */
node = node->next;
if(node == head) break;
}
}
The print_list can run and print the id correctly if the code between BEG and END are marked. Otherwise, it cause segment fault.
After using gdb, it says "Cannot access memory at address 0x0." I can't figure out why the inner variable time_stamp would be at the address 0x0. Would any please tell me where did I do it wrong?
I appreciate any advice,
Thank you very much.