Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why segmentation fault (core dumped) when I cin a string into node->name?

Segmentation fault (core dumped) when I getline(cin, node->name).

I fixed by declare a str string in my input function, then node->name = str. But ran to the line cin >> node->year and still hit Segmentation fault.

struct client
{
    int code;
    string name;
    int year;
    float maths, physics, chemistry;
    struct client *next;
};

struct client* input()
{
    struct client *node = (struct client *)malloc(sizeof(struct client));

    cout << "Code: ";
    cin >> node->code;

    cout << "Name: ";
    cin.ignore();
    getline(cin, node->name);

    cout << "Year: ";
    cin >> node->year;

    cout << "Maths, Physics, Chemistry: ";
    cin >> node->maths >> node->physics >> node->chemistry;

    node->next = NULL;

    return node;
}
like image 763
Nguyễn Á Tân Avatar asked Jan 27 '23 07:01

Nguyễn Á Tân


1 Answers

Since you use malloc to allocate your memory, nothing in the new node will be initialized. In particular string name won't be initialized properly and that will cause problems when you try to use it, because any functionality involving it relies on the fact that the string has been properly constructed. Instead of this:

struct client *node = (struct client *)malloc(sizeof(struct client));

Do this:

client *node = new client;

This way the node (and the name) within are properly initialized.

like image 152
Blaze Avatar answered Feb 16 '23 00:02

Blaze