The stack is displaying garbage values - c

I have a stack.There is some error in the program when I try to display the stack.
Please help me find the mistake in the program.The stack is displaying garbage values.
The stack has a push,pop and display function.I have created a menu based program.
But it is not displaying correctly.There could be a semantic error in the program.
#include<stdio.h>
#include<stdlib.h>
#define STACKSIZE 100
struct stack
{
int top;
int items[STACKSIZE];
};
void pop(struct stack *ps)
{ int i,x=0;
if (ps->top == -1) // check if the stack is the empty
printf("STACK EMPTY Cannot DELETE..");
else
{
x=ps->items[ps->top]; //delete the element
printf("popped element is %d\n",x);
--(ps->top); //decrement top
}
}
void display(struct stack *ps){
int i,x=0;
if (ps->top==-1) // check if the stack is the empty
printf("STACK EMPTY ");
else
{
for (i=ps->top;i>=0;i--) // displays the elements from top
printf("%d",ps->items[i]);
}
}
int push(struct stack *ps,int ele)
{int i,x=0;
if(ps->top==STACKSIZE-1)//check if the stack is full
{
printf("stack full cannot insert");
return 0;
}
else
{
++(ps->top); //increment the top
ps->items[ps->top]=x;//insert the element
}
}
int main()
{
struct stack s;
s.top=-1;
int ele=0;
char ch;
while(1)
{
printf("enter option\np.push\nq.pop\nd.display\ne.exit");
scanf("%c",&ch);
switch(ch){
case 'p':
printf("enter ele");
scanf("%d",&ele);
push(&s,ele);
break;
case 'q':
pop(&s);
break;
case 'd':
display(&s);
break;
case 'e':
exit(0);
default:
break;
}
}
}

You are assigning x to ps->items[ps->top] instead of ele when you push an element onto the stack

Related

Implementation of stack using linked list

I am getting a "Function should return a value" error at the 91st line of the code in Turbo C++, please help me as I have to submit my project, I know that Turbo C++ is a very old compiler but that's what our University Teacher recommends so I cant do nothing in that
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
#include <stdio.h>
#include <conio.h>
struct stack
{
int element;
struct stack *next;
} * top;
void push(int);
int pop();
void display();
void main()
{
int num1, num2, choice;
while (1)
{
clrscr();
printf("Select a choice from the following:");
printf("\n[1] Push an element into the stack");
printf("\n[2] Pop out an element from the stack");
printf("\n[3] Display the stack elements");
printf("\n[4] Exit\n");
printf("\n\tYour choice: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
{
printf("\n\tEnter the element to be pushed into the stack: ");
scanf("%d", &num1);
push(num1);
break;
}
case 2:
{
num2 = pop();
printf("\n\t%d element popped out of the stack\n\t", num2);
getch();
break;
}
case 3:
{
display();
getch();
break;
}
case 4:
exit(1);
break;
default:
printf("\nInvalid choice !\n");
break;
}
}
}
void push(int value)
{
struct stack *ptr;
ptr = (struct stack *)malloc(sizeof(struct stack));
ptr->element = value;
ptr->next = top;
top = ptr;
return;
}
int pop()
{
if (top == NULL)
{
printf("\n\STACK is Empty.");
getch();
exit(1);
}
else
{
int temp = top->element;
top = top->next;
return (temp);
}
}
void display()
{
struct stack *ptr1 = NULL;
ptr1 = top;
printf("\nThe various stack elements are:\n");
while (ptr1 != NULL)
{
printf("%d\t", ptr1->element);
ptr1 = ptr1->next;
}
}
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
The compiler is complaining because you don’t have a return statement outside of the if statement. Even though you call exit in the if branch, syntactically speaking that’s just another function call; structurally, the compiler sees a pathway where you reach the closing } of the function body without a return statement.
You want to make sure the return is reachable outside the body of the if-else statement, and the best way to do it is take the else branch out of the statement entirely:
int pop( void )
{
int temp;
if ( !top )
{
fputs( "Stack is empty", stderr );
exit( 1 );
}
temp = top->element;
top = top->next;
return temp;
}
you can change your pop function as below ( assuming you are not storing -1 as an element in the stack)
int pop()
{
if (top == NULL)
{
printf("\n\STACK is Empty.");
getch();
return -1;// or other invalid value which indicates stack empty
}
else
{
int temp = top->element;
top = top->next;
return (temp);
}
}
and at the place you are calling modify as following
case 2:
{
num2 = pop();
if(num2 != -1) {
printf("\n\t%d element popped out of the stack\n\t", num2);
getch();
}else{
printf("Stack is Empty\n");
exit(1);
}
break;
}

how to give a identification to a element on FIFO queue in C? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have this queue code on C. It may represent a FIFO, but I don't know how to insert a "password" for each new different entry, something like an identifier. Does anyone have any idea?
There is my code:
#define true 1
#define false 0
#include<stdio.h>
#include<conio.h>
#include <stdlib.h>
#include<process.h>
struct queue_point
{
int element;
struct queue_point* n;
};
struct queue_point *f_ptr = NULL;
int is_que(void);
void add_ele(int);
int remove_ele(void);
void show_ele();
int main(void)
{
int ele,choice,j;
printf("1 To insert an element");
printf("\n2 To remove an element");
printf("\n3 To display all the elements");
printf("\n4 Exit\n");
while(1)
{
printf("\nEnter your choice: ");
scanf("%d", &choice);
switch(choice)
{
case 1:
{
printf("\nElement to be inserted: ");
scanf("%d",&ele);
add_ele(ele);
break;
}
case 2:
{
if(!is_que())
{
j=remove_ele();
printf("\n%d is removed from the queue",j);
printf("\n");
}
else
{
printf("\nQueue is Empty.\n");
}
break;
}
case 3:
show_ele();
break;
case 4:
exit(1);
break;
default:
printf("\nInvalid choice.\n");
break;
}
}
}
/* Function to check if the queue is empty*/
int is_que(void)
{
if(f_ptr==NULL)
return true;
return false;
}
/* Function to add an element to the queue*/
void add_ele(int element)
{
/*dynamically allocate the memory*/
struct queue_point *queue = (struct queue_point*)malloc(sizeof(struct queue_point));
queue->element = element;
queue->n = NULL;
if(f_ptr==NULL)
{
f_ptr = queue;
}
else
{
struct queue_point* ptr;
ptr = f_ptr;
for(ptr=f_ptr ;ptr->n!=NULL; ptr=ptr->n);
ptr->n = queue;
}
}
/* Function to remove an element from the queue*/
int remove_ele()
{
struct queue_point* queue=NULL;
if(is_que()==false)
{
int j = f_ptr->element;
queue=f_ptr;
f_ptr = f_ptr->n;
/*If you have allocated a memory block with the functions malloc(), calloc()
or realloc() then you need to free the previously allocated memory.*/
free (queue);
return j;
}
else
{
printf("\nQueue is empty.\n");
return -9999;
}
}
/* Function to display the queue*/
void show_ele()
{
struct queue_point *ptr=NULL;
ptr=f_ptr;
if(is_que())
{
printf("\nQUEUE is Empty.\n");
return;
}
else
{
printf("\nElements present in Queue are: ");
while(ptr!=NULL)
{
printf("%d\t",ptr->element);
ptr=ptr->n;
}
printf("\n");
}
}
You can modify your structure like this:
struct queue_point
{
int element;
int identifier;
struct queue_point* n;
};
If you prefer to use a string for your identifier, you'd write char identifer[SIZE_OF_YOUR_CHOICE] .

C fifo linked list char push

I'm currently trying to understand fifo linked list and found example here Example , and I'm trying to input char instead of int
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
struct Node
{
char Data;
struct Node* next;
}*rear, *front;
void delQueue()
{
struct Node *temp, *var=rear;
if(var==rear)
{
rear = rear->next;
free(var);
}
else
printf("\nQueue Empty");
}
void push(char *value)
{
struct Node *temp;
temp=(struct Node *)malloc(sizeof(struct Node));
temp->Data=value;
if (front == NULL)
{
front=temp;
front->next=NULL;
rear=front;
}
else
{
front->next=temp;
front=temp;
front->next=NULL;
}
}
void display()
{
struct Node *var=rear;
if(var!=NULL)
{
printf("\nElements are as: ");
while(var!=NULL)
{
printf("\t%d",var->Data);
var=var->next;
}
printf("\n");
}
else
printf("\nQueue is Empty");
}
int main()
{
int i=0;
char ch;
front=NULL;
printf(" \n1. Push to Queue");
printf(" \n2. Pop from Queue");
printf(" \n3. Display Data of Queue");
printf(" \n4. Exit\n");
while(1)
{
printf(" \nChoose Option: ");
//scanf("%d",&i);
ch = getchar();
switch(ch)
{
case '+':
{
char value[20];
printf("\nEnter a valueber to push into Queue : ");
scanf("%s", value);
push(value);
printf("%s",value);
display();
break;
}
case '-':
{
delQueue();
display();
break;
}
case '*':
{
display();
break;
}
case '$':
{
exit(0);
}
default:
{
printf("\nwrong choice for operation");
}
}
}
}
I can't understand this warning on line 26: warning: assignment makes integer from pointer without a cast
I can input text, for example: "Hello world", but when I want to display it, it is showed as "-9".
I am really confused.
Data is defined as char, but your assigning a char * (char pointer) to it. That creates the warning, and surely won't work as you expect.
In your Node struct, the value is of type char, but you're assigning a char* to it instead. This is why you get the warning, and why printing things doesn't come out right.

STACK in c program. pop operation not working

Guys what is wrong with this program. I am having problems with pop operation, it shows an extra value even after stack is empty. ??
void initstack (struct stack * p, int maxSize)
void push (struct stack * p, int item)
int pop (struct stack * p)
void display (struct stack p)
struct stack
{
int * a;
int top;
int maxSize;
};
Note:using d above structure and functions are mandatory..
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
struct stack {
int * a;
int top;
int maxSize;
};
void initstack(struct stack * p, int maxSize);
void push(struct stack * p, int item);
int pop(struct stack * p);
void display(struct stack p);
int StackIsEmpty(struct stack * p);
int StackIsFull(struct stack * p);
void printMenu();
int main() {
struct stack p;
int data,ch, data1, m;
printf("Enter the maximum size of the stack\n");
scanf("%d",&m);
initstack(&p,m);
do {
printMenu();
printf("Enter your choice\n");
scanf("%d",&ch);
switch(ch) {
case 1:
printf("Enter the element to be pushed\n");
scanf("%d",&data);
push(&p, data);
break;
case 2:
data1 = pop(&p);
if(data1 != -1000)
printf("The popped element is %d\n",data1);
break;
case 3:
printf("The contents of the stack are");
display(p);
printf("\n");
break;
default:
exit(0);
}
} while(1);
return 0;
}
void printMenu()
{
printf("Choice 1 : Push\n");
printf("Choice 2 : Pop\n");
printf("Choice 3 : Display\n");
printf("Any other choice : Exit\n");
}
void initstack(struct stack * p, int maxSize) {
int *newContents;
newContents=(int *)malloc(sizeof(int)*maxSize);
p->a=newContents;
p->maxSize=maxSize;
p->top=-1;
}
void push(struct stack * p, int item) {
if(StackIsFull(p))
{
printf("Stack is full\n");
}
p->a[++p->top]=item;
}
void display(struct stack p) {
int i;
struct stack *b=&p;
if(StackIsEmpty(b))
printf(" {}");
for(i=0;i<b->top;i++)
{
printf(" %d",b->a[i]);
}
}
int pop(struct stack * p) {
if(StackIsEmpty(p))
{
printf("Stack is empty\n");
return -1000;
}
else
return p->a[--p->top];
}
int StackIsEmpty(struct stack *p)
{
return p->top == -1; //p->top==-1;
}
int StackIsFull(struct stack *p)
{
return p->top >= p->maxSize-1;
}
Let's look at your push and pop operations:
p->a[++p->top]=item; // push
p->a[--p->top]; // pop
Let's assume the stack is empty and top is -1. When you do a push, you increment top to 0 and write your element to p->a[0]. When you pop that element, you first decrement top back to -1, and then try to access the element p->a[-1].
This is a problem. Not only are you popping the wrong element, you're accessing an element outside the range of your array and invoking undefined behavior.
You need to change the stack pointer after you access the element you want, like so:
p->a[++p->top] = item; // push
item = p->a[p->top--]; // pop
For array-based stacks, it's actually a little more natural for the stack to grow "downwards", like so:
p->top = p->maxSize = maxSize; // init
if ( p->top ) // p->top != 0 means room left on the stack
p->a[--p->top] = item; // push
if ( p->top < p->maxSize ) // p->top < p->maxSize means elements left on stack
return p->a[p->top++]; // pop
This way, you don't run the risk of accessing an element outside the range of the array. p->top will always be between 0 and maxSize - 1.
Finally, a style note:
You don't need to cast the result of malloc; it just adds visual clutter, and in some cases can suppress a useful diagnostic. You can clean it up by simply writing:
/**
* Whitespace is your friend. Use it.
*/
newContents = malloc( sizeof *newContents * maxSize );
sizeof *newContents is the same as sizeof (int); this way, if you ever decide to change the type of the stack array, you don't have to worry about changing the malloc call itself. Saves some maintenance headaches, reads a little easier.
Edit
Here's part of what's causing your headaches:
void push(struct stack * p, int item) {
if(StackIsFull(p))
{
printf("Stack is full\n");
}
p->a[++p->top]=item; // DANGER WILL ROBINSON!
}
If the stack is full you print a warning, and then you push the element anyway.
You need an else branch in there
void push(struct stack * p, int item)
{
if(StackIsFull(p))
{
printf("Stack is full\n");
}
else
{
p->a[++p->top]=item;
}
}
Thanks guys, I fixed it.. works fine. thanks for all ur suggestions.
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
struct stack {
int * a;
int top;
int maxSize;
};
void initstack(struct stack * p, int maxSize);
void push(struct stack * p, int item);
int pop(struct stack * p);
void display(struct stack p);
int StackIsEmpty(struct stack * p);
int StackIsFull(struct stack * p);
void printMenu();
int main() {
struct stack p;
int data,ch, data1, m;
printf("Enter the maximum size of the stack\n");
scanf("%d",&m);
initstack(&p,m);
do {
printMenu();
printf("Enter your choice\n");
scanf("%d",&ch);
switch(ch) {
case 1:
printf("Enter the element to be pushed\n");
scanf("%d",&data);
push(&p, data);
break;
case 2:
data1 = pop(&p);
if(data1 != -1000)
printf("The popped element is %d\n",data1);
break;
case 3:
printf("The contents of the stack are");
display(p);
printf("\n");
break;
default:
exit(0);
}
} while(1);
return 0;
}
void printMenu()
{
printf("Choice 1 : Push\n");
printf("Choice 2 : Pop\n");
printf("Choice 3 : Display\n");
printf("Any other choice : Exit\n");
}
void initstack(struct stack * p, int maxSize) {
int *newContents;
newContents=malloc(sizeof(int)*maxSize);
p->a=newContents;
p->maxSize=maxSize;
p->top=-1;
}
void push(struct stack * p, int item) {
if(StackIsFull(p))
{
printf("Stack is full\n");
}
else
{
p->a[++p->top]=item; //FIXED LINE, ELSE BLOCK ADDED
}
}
void display(struct stack p) {
int i;
struct stack *b=&p;
if(StackIsEmpty(b))
printf(" {}");
for(i=0;i<=b->top;i++) //FIXED PREVIOUSLY for(i=0;i<b->top;i++)
{
printf(" %d",b->a[i]);
}
}
int pop(struct stack * p) {
if(StackIsEmpty(p))
{
printf("Stack is empty\n");
return -1000;
}
else
return p->a[p->top--]; //FIXED PREVIOUSLY p->a[--p->top];
}
int StackIsEmpty(struct stack *p)
{
return p->top < 0; //FIXED PREVIOUSLY p->top==-1;
}
int StackIsFull(struct stack *p)
{
return p->top >= p->maxSize-1;
}
Your display logic is faulty. It has an off-by-one error and skips the topmost element.
return p->a[--p->top];
In this part I think you should first
int result = p->a[p->top];
then
p->top --;
return result;
I had same issue and that helped me.
It hink the problem is related to push and pop functions. Both use preincrements, so the last item you push is not the first item you pop.
Your push does: first increment top, then store value in a[top]. So top is pointing to the newly pushed element.
Your pop does: first decrement top, then retrieve the value at a[top]. The value retrieved won't be the last pushed, but the previous-to-last. top keeps pointing at this very same value.
My suggestion: leave push as is, and change pop as this:
int pop(struct stack * p) {
if(StackIsEmpty(p))
{
printf("Stack is empty\n");
return -1000;
}
else
return p->a[p->top--]; /* post-increment!! */
}
So, push will leave top pointing at the last pushed value. pop will retrieve this value, then decrement top, leaving it pointing at the next value to retrieve.

Why is this program having a runtime crash when I push data? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I am creating a stack. But when trying to push data into the stack it is having a runtime crash.Can you explain why is this happening and provide me the correct code? This is my program-
#include<stdio.h>
#include<stdlib.h>
struct ArrayStack* create_stack(void);
int IsStackFull(struct ArrayStack *);
int IsStackEmpty(struct ArrayStack *);
struct ArrayStack * push(struct ArrayStack *,int );
struct ArrayStack
{
int capacity;
int top;
int *array;
};
int main()
{
int choice1=0;
int choice=0,data=0,var=0;
struct ArrayStack *s=create_stack();
printf("\n STACK CREATED");
do
{
printf("\n 1= Test If Stack Is Empty or not");
printf("\n 2= Test If Stack Is Full Or Not");
printf("\n 3= Push Element Into The Stack");
printf("\n 4= Pop Element from the stack");
printf("\n\n Enter yOur choice:: ");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
var=IsStackEmpty(s);
if(var)
{
printf("\n Yes Stack Is eMpty for Now");
break;
}
else
{
printf("\n No Stack Is Not Empty ");
break;
}
}
case 2:
{
var=IsStackFull(s);
if(var)
{
printf("\n Yes Stack Is Full for Now");
break;
}
else
{
printf("\n No Stack Is Not Full ");
break;
}
}
case 3:
{
printf("\n Provide The Input For stack::");
scanf("%d",&data);
struct ArrayStack *s=push(s,data);
printf("\n Element inerted into the Stack");
break;
}
case 4:
{
var=pop(s);
if(var)
{
printf("\n Removed The element from the Stack");
break;
}
break;
}
default:
{
printf("\n Wrong Input");
}
}
printf("\n Do you want to countinue(1 for yes/0 for no):: ");
scanf("%d",&choice1);
}while(choice1);
}
struct ArrayStack* create_stack()
{
struct ArrayStack *s=(struct ArrayStack *)malloc(sizeof(struct ArrayStack));
if(!s)
{
printf("\nNot enough Memory");
return NULL;
}
s->capacity=4;
s->top=-1;
s->array=(int *)malloc(s->capacity*sizeof(int));
if(!s->array)
{
return NULL;
}
else
return s;
}
int IsStackEmpty(struct ArrayStack *s)
{
if(s->top=-1)
return 1;
else
return 0;
}
int IsStackFull(struct ArrayStack *s)
{
if(s->top==s->capacity-1)
{
return 1;
}
return 0;
}
struct ArrayStack * push(struct ArrayStack *s,int data)
{
if(IsStackFull(s))
{
printf("\n Sorry. The stack is full already");
}
else
{
s->array[++s->top]=data;
printf("\n Element Inserted Successfully");
return s;
}
}
int pop(struct ArrayStack *s)
{
if(IsStackEmpty(s))
{
printf("\n Sorry. Trying to pop element from an empty stack");
return 0;
}
else
{
s->array=s->array[s->top--];
return 1;
}
}
In your Push element case, you are creating one local instance of s, which is confusing with s you have created before do..while loop.
Change code in switch case 3 to
s=push(s,data); //(remove struct ArrayStack *)
Your if test in IsStackEmpty() is doomed. With
if(s->top=-1)
You are assigning instead of comparing. This always evaluates to true, so your IsStackEmpty() function always says the stack is empty. Use == instead.
Your pop function is wrong. You don't want to change the pointer returned by malloc, given your structure definition, I believe you would want to decrement top, and return the popped element (notice you never return the popped element...)
int pop(struct ArrayStack *s)
{
if(IsStackEmpty(s))
{
printf("\n Sorry. Trying to pop element from an empty stack");
return 0;
}
else
{
return s->top--;
}
}
This assumes that 0 is never pushed, so you can distinguish error conditions from normal flow. Otherwise, you'll have to find some other way to report errors.
case 3:
{
printf("\n Provide The Input For stack::");
scanf("%d",&data);
struct ArrayStack *s=push(s,data);
printf("\n Element inerted into the Stack");
break;
}
In above code, ArrayStack s is not initialised and it is used in IsStackEmpty() functions , so it crashes with access violation, use the ArrayStack s already initialised in main program using Create_Stack()
struct ArrayStack *s=create_stack();

Resources