[Solved] Inserting a single element in a linked list gives a segmentation fault – C++


Your head parameter in insertNode function should be a reference (or a pointer to pointer to Node). Beacause in the current form, it is an input parameter, but you need to be in-out parameter. It means that in the current code, your aNode variable is NULL and is always stays NULL.

I recommend this:
void insertNode(int data, Node &head)

Then you create an object in main this way: Node aNode;

It will allow you to update the existing variable directly and you don’t need a return value. Also, this way it will be a little bit more C++like, your original code is more like a plain C code.

Or if you want to write it in plain C:
void insertNode(int data, Node **head)

Then you change the call from main: insertNode(2, &aNode);

3

solved Inserting a single element in a linked list gives a segmentation fault – C++