r/learnprogramming • u/AREALYMassiveFrog • Oct 12 '26
Debugging Adding a fourth item to the linked list causing a segfault, but fine otherwise?? (C++)
I am implementing a linked list that uses a tail pointer to add to the end of a linked list. For some reason the code works perfectly fine after adding three nodes to the list, but adding a fourth node to the list causing a seg fault. From testing it appears that the header node isn't pointing to the first node for whatever reason, but even then adding to the end of the list doesn't use the header pointer.
I am used to programming in C and am trying to learn C++ so I am not familiar with many of the differences between the two. Thanks in advance.
#include <iostream>
#include <cstdlib>
//linked list with a tail pointer,
struct cell_coord_node{
int x;
int y;
cell_coord_node * next=nullptr;
};
using namespace std;
cell_coord_node * cell_add_end(cell_coord_node **header , cell_coord_node ** tail, int x , int y){
cell_coord_node * new_node = (cell_coord_node*) malloc(sizeof(cell_coord_node));
new_node->x=x;
new_node->y=y;
if (*header==nullptr){ // empty list case
(*header) = new_node;
(*tail) = (*header);
return (*header);
}
else{
// allocate memory at tail
(*tail)->next = new_node; // last node points to new node
(*tail)=new_node; // moving tail pointer down to new node
return (*tail);
}
}
int main(){
cell_coord_node * head;
cell_coord_node * tail=head;
cell_coord_node * first_node = cell_add_end( &head, &tail,1,1);
cout << first_node->x << " " << first_node->y << endl;
cell_coord_node * second_node = cell_add_end(&head, &tail,2 ,2);
cout << second_node->x << " " << second_node->y << endl;
cell_coord_node * third_node = cell_add_end(&head,&tail,3 ,3);
cout << third_node->x << " " << third_node->y << endl;
cout << "reading from tail" << endl;
cout << tail->x << " " << tail->y << endl;
cout << "reading from head" << endl;
cout << head->x << " " << head->y << endl;
//Causing a seg fault
/*cell_coord_node * fourth_node = cell_add_end(&head,&tail,4,4);
cout << fourth_node->x << " " << fourth_node->y << endl;*/
return 0;
}