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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With