• Advertisement
Sign in to follow this  

Pointer Problem

This topic is 3405 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I am trying to just print a list of numbers from a linked list but for some reason the program goes ahead and prints the list then crashes and I am not sure as to why. I believe it is because the pointer is trying to access a NULL pointer but I have a condition in my loop that shouldnt allow that to happen. Here is my code:
#include <iostream>
#include <cassert>
using namespace std;

struct Node
{
	int data;
	Node *link;
};

typedef Node* NodePtr;

void head_insert(NodePtr& head, int the_number);
/* Precondition: The pointer variable head points to the head of a linked list.
 * Postcondition: A new node containing the_number has been added at the head of the linked list
 */

void printList(NodePtr head);

int main()
{
	bool end = false;
	char answer;
	int num;

	NodePtr head;
	while(!end)
	{
		cout << "Enter in a number to be inserted into the list:\n";
		cin >> num;
		head_insert(head, num);
	
		printList(head);

		cout << "Would you like to insert again?(Y/N)\n";
		cin >> answer;
		if(answer == 'n' || answer == 'N')
			end = true;
	}
}

void head_insert(NodePtr& head, int the_number)
{
	NodePtr temp_ptr;
	temp_ptr = new Node;

	temp_ptr->data = the_number;

	temp_ptr->link = head;
	head = temp_ptr;
}

void printList(NodePtr head)
{
	NodePtr here;

	cout << "List contains:\n";
	for(here = head; here != NULL; here = here->link)
		cout << (here->data) << ' ';
}

Share this post


Link to post
Share on other sites
Advertisement
Well... Without a detailed look at your code... The line;

NodePtr head;

declares a pointer to Node, but the pointer points to what??!! A memory location probably outside your code/data space... Hence the crash.

Initialize head to NULL.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement