Click here to Skip to main content
15,891,883 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
WHEN I RUN THE COMPILED FILE ITS SHOWING SEGMENTATION FAULT.
WHAT'S WRONG WITH THIS?
PLEASE HELP!!!


C++
#include<stdio.h>
#include<malloc.h>
struct node{
	int data;
	struct node *link;
	}*top,*ptr,*start;
main()
{	
	top->link=NULL;
	int choice,info;
	printf("CHOOSE AN OPTION\n");
	scanf("%d",&choice);
	printf("1.PUSH AN ELEMENT\n");
	printf("2.POP AN ELEMENT\n");
	printf("3.DISPLAY\n");
	printf("4.EXIT\n");
	switch(choice)
	{
		case 1:
		printf("ENTER THE ELEMENT YOU WANT TO PUSH\n");
		scanf("%d",&info);
		push(info);
		break;
		/*case 2:
		pop(top->data);
		break;*/
		case 3:
		display();
		break;
	}
}
push(int info)
{	
	if(top->link!=NULL)
	{
		ptr->link=top;
		top=malloc(sizeof(struct node));
		top->data=info;
		top->link=NULL;
	}
	else
	{
	start->link=top;
	top->data=info;
	top->link=NULL;
	}
	
}

display()
{	ptr=start;
	while(ptr->link!=NULL)
	{	
		int info;
		info=(ptr->data);
		printf("%d\t",info);
		ptr=ptr->link;
	}
}


WHEN I RUN THE COMPILED FILE ITS SHOWING SEGMENTATION FAULT.
WHAT'S WRONG WITH THIS?
PLEASE HELP!!!
Posted
Updated 14-Oct-11 11:31am
v2
Comments
Sergey Alexandrovich Kryukov 14-Oct-11 17:27pm    
You don't have to shout. On the Web, all-caps is considered shouting, so this is very impolite. Please remove it.
Also, did you run it under debugger? Please indicate the line of the code when it happens.
--SA
Chuck O'Toole 14-Oct-11 19:03pm    
You have lots of printf's other things going on, do you want to give folks a clue as to how far the program got before it blew up. What was the print outs before the crash?

1 solution

Look at the very first line of main. Where top comes from? You never allocated memory for this pointer.

—SA
 
Share this answer
 
Comments
bhrgvnkl 14-Oct-11 18:03pm    
i had allocated memory for that right after i defined the structure
Chuck O'Toole 14-Oct-11 19:01pm    
So, in other words, you aren't showing us the actual program. How the heck do you expect any help then? Are we to guess at what's wrong?
Sergey Alexandrovich Kryukov 14-Oct-11 23:20pm    
No, you did not, not in the code you show.
--SA
Richard MacCutchan 15-Oct-11 6:07am    
No, you declared top as a pointer but never allocated anything to it, so top points to nothing.
Sergey Alexandrovich Kryukov 15-Oct-11 19:47pm    
Exactly,
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900