简体   繁体   中英

segment fault when assigning a new allocated memory to a struct pointer

struct Student {
public:
    string name;
    string family;
    string stdno;
    string ncode;
    float average;
    float age;
    struct Student *FL;
} *start, *cur, *p;

p = new struct Student;
    cur->FL = p;
    p->FL = NULL; // p->FL = nullptr in c++11
    cur = p;

I try assigning a new memory allocated to a structure pointer,It seems there is no issue but I get segment fault when cur->FL = p; ran, Am I doing something wrong here ?

Assuming your code is all at global scope, your cur pointer got initialized to null and dereferencing it to access the FL member will very likely break things. You need to make sure you initialize cur .

cur has not been assigned anything to point to

cur = p;

Needs to be before p->FL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM