Why does this code causes segmentation fault only because of a "cout"?

Why does this code cause no error
#include
using namespace std;

struct ListNode
{
	int val;
	ListNode *next;
	ListNode() : val(0), next(nullptr) {}
	ListNode(int x) : val(x), next(nullptr) {}
	ListNode(int x, ListNode *next) : val(x), next(next) {}
};

ListNode* removeNthFromEnd(ListNode* head, int n)
{
	int count=0;
	ListNode *temp, *temp2;
	while(temp != NULL)
	{
		temp = temp->next;
		count++;
	}
	return head;
}
void printList(ListNode* n)
{
	while (n != NULL)
	{
		cout << n->val << " ";
		n = n->next;
	}
	cout << "\n";
}
int main()
{
	ListNode *head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
	printList(head);

	ListNode *head2 = removeNthFromEnd(head, 2);
	printList(head2);
}

while this code does?
#include
using namespace std;

struct ListNode
{
	int val;
	ListNode *next;
	ListNode() : val(0), next(nullptr) {}
	ListNode(int x) : val(x), next(nullptr) {}
	ListNode(int x, ListNode *next) : val(x), next(next) {}
};

ListNode* removeNthFromEnd(ListNode* head, int n)
{
	int count=0;
	ListNode *temp, *temp2;
	while(temp != NULL)
	{
		temp = temp->next;
		count++;
	}
	return head;
}
void printList(ListNode* n)
{
	while (n != NULL)
	{
		cout << n->val << " ";
		n = n->next;
	}
	cout << "\n";
}
int main()
{
	ListNode *head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
	printList(head);
	cout << "\n"; //THIS IS THE LINE THAT IS CAUSING THE ERROR
	ListNode *head2 = removeNthFromEnd(head, 2);
	printList(head2);
}

Only difference between both is that one line only

Using an newline cannot be a reason for SIGSEGV, and as far I can see this code does not do anything, it will just print the same list twice.
Can you explain what is the significance of this code and where are you executing/submitting it ?

I am not submitting this code. I am just trying to understand the weird behavior of this code. Such as:

  • If i remove the new line, it does not cause segment fault and works perfectly fine.
  • I have not assigned head to temp yet still if i don’t add the new line, function works exactly as intended. temp is referring to the head of list even though i have not assigned it. Why?
  • If i do add a new line, temp is now suddenly pointing to a random location and hence causing segment fault. Again, why?

Purpose of this code is nothing i guess. I mean it’s counting the number of elements in list but that’s not important.

Which compiler are you using ?
you can try to run both codes on codechef ide and check if error persists.

hmmmmm. I was using g++ earlier. I also tried it on onlinegdb. On codechef ide, it isn’t causing error. I guess it’s just undefined behavior then ;_;

Usage of uninitialised pointers is absolutely undefined behaviour, yes :slight_smile:

1 Like