I transplanted a doubly linked list from the linux kernel, but I found some problems when testing the inserted elements of the linked list,the test code is as follows.when i run the test case,i find the result is so weirdenter image description here.However I put the stu_list member at the beginning of struct student,the result is normalenter image description here.Please tell me why there is such a result and the principle,thanks!
struct list_head {
struct list_head *next, *prev;
};
struct student {
int id;
int grades;
struct list_head stu_list;
};
int main(void) {
struct student stu1, stu2;
struct student *p;
struct list_head *pos;
INIT_LIST_HEAD(&stu1.stu_list);
INIT_LIST_HEAD(&stu2.stu_list);
for (volatile int i = 0; i < 6; i++) {
p = (struct student *) malloc(sizeof(struct student));
p->id = i;
p->grades = 90 + i;
list_add_tail(&p->stu_list, &stu1.stu_list);
}
printf("list add result:\n");
list_for_each(pos, &stu1.stu_list) {
printf("ID = %d,grades = %d\n", ((struct student *) pos)->id, ((struct student *) pos)->grades);
}
return 0;
}