I got run-time error for the following code. I am just starting to get familiar with linked list. Can any one point out what's the problem here? thanks

#include "stdafx.h"
#include<iostream>
using namespace std;

struct node
{
int data;
node * next;
};

node* buildonetwothree()  
{
node* head=NULL;          
node* second=NULL;        
node* third=NULL;         


head->data=1;
head->next=second;

second->data=2;
second->next=third;

third->data=3;
third->next=NULL;
return head;           
}


int length(node* head) 
{

node* moving=head;
int count=0;
while(moving!=NULL)    
{moving=moving->next;
count++;}
return count;
}

void main()
{
node* head=NULL;
head=buildonetwothree();
cout<<length(head);

}

You haven't allocated any memory for your pointers

node* buildonetwothree()
{
node* head=NULL;
node* second=NULL;
node* third=NULL;

head->data=1;

head->next=second;
second->data=2;
second->next=third;
third->data=3;
third->next=NULL;

return head;
}

thanks, I changed

node* head=NULL;         
node* second=NULL;       
node* third=NULL;

to

node* head=new node;  
node* second=new node;
node* third=new node;

now it works, but where should I deallocate the dynamic allocated memory? at the end of the main program?

thanks, I changed

node* head=NULL;         
node* second=NULL;       
node* third=NULL;

to

node* head=new node;  
node* second=new node;
node* third=new node;

now it works, but where should I deallocate the dynamic allocated memory? at the end of the main program?

You really should implement your nodes as classes and let the destructor's worry about freeing up allocated memory..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.