Reputation: 15527
Could anyone tell me why am i getting error when I try to push
#include <stdio.h>
typedef struct Element
{
struct Element *next;
void *data;
}Element;
bool createStack(Element **stack)
{
*stack = NULL;
return true;
}
bool push (Element **stack, void *data)
{
Element *new_element = new Element;
if(!new_element)
{
printf("Memory allocation error in push");
return false;
}
new_element->data = data;
new_element->next = *stack;
*stack = new_element;
return true;
}
bool pop (Element **stack, void *popped_data)
{
if(!*stack)
{
printf("Stack empty");
return false;
}
Element *new_head = new Element;
popped_data = (*stack)->data;
new_head = (*stack)->next;
delete *stack;
return true;
}
bool emptyStack(Element **stack)
{
if(!*stack)
{
printf("Stack empty");
return false;
}
Element *delete_ele;
while(*stack)
{
delete_ele=*stack;
*stack = delete_ele->next;
delete delete_ele;
}
return true;
}
int main()
{
int i,*j;
Element *stacka = new Element;
while(i!=5)
{
printf("Enter ur choice \n");
scanf("%d",&i);
if(i==1)
{
if(createStack(&stacka))
{
printf("yes");
}
}
if(i==2)
{
*j=2;
if(push(&stacka,j))
{
printf("yes");
}
}
if(i==3)
{
if(pop(&stacka,j))
{
printf("yes %d",*j);
}
}
if(i==4)
{
if(emptyStack(&stacka))
{
printf("yes");
}
}
}
return 0;
}
Thanks for the help running it on ubuntu
Upvotes: 0
Views: 185
Reputation: 477494
When you declare int i,*j;
, j
is just an uninitialized pointer that doesn't point to a valid memory location. Later, when you say *j=2;
, you dereference that pointer, which results in undefined behaviour.
You have to assign a meaningful location to j
, like so:
int j_content;
int *j = &j_content;
Upvotes: 1
Reputation: 11922
It's in this line
*j = 2;
j
is uninitialized at that point.
You should either push &k
where k
is an int
, or initialize j = new int
. Memory leak avoidance is up to you in the latter case.
Upvotes: 5