So, I was working on a standard stack program in C with push, pop etc. The code compiles fine but as soon as I run it, it crashes and a 'stopped working' message is shown. I am working on a Dev C++ application on a windows system. The code is given below:
#include <stdio.h>
#include <stdlib.h>
#define MAX 10
struct stack {
int items[MAX];
int top;
};
typedef struct stack st;
void createemptyStack(st *s) {
s->top = -1;
}
int isEmpty(st *s) {
if (s->top == -1)
return 1;
else
return 0;
}
int isFull(st *s) {
if (s->top == MAX - 1)
return 1;
else
return 0;
}
int push(st *s) {
int newitem;
printf("Enter the value you want to push");
scanf("%d", &newitem);
if (isFull(s)) {
printf("Stack is full");
} else {
s->top++;
s->items[s->top] = newitem;
}
}
void pop(st *s) {
if (isEmpty(s)) {
printf("Stack is empty");
} else {
printf("Items popped %d", s->items[s->top]);
s->top--;
}
}
int main() {
int ch;
int loop = 1;
st *s;
createemptyStack(s);
do {
printf("\n ***STACK OPERATIONS");
printf("\n 1. PUSH");
printf("\n 2. POP");
printf("\n 3. EXIT");
printf("\n ***************");
printf("\n Enter your choice: ");
scanf("%d", &ch);
switch (ch) {
case 1:
push(s);
break;
case 2:
pop(s);
break;
case 3:
printf("Visit again");
loop = 0;
exit(0);
default:
printf("Invalid choice");
}
} while(loop);
getch();
}
Would really be helpful for me if you can help me in this matter. I think the problem might reside in the do / while
loop but I am not sure. Would like some opinions on this matter.
st *s;
you are not allocating memory to *s
, change it to
st *s = malloc(sizeof(*s));
or
st s;
createemptyStack(&s)
The value of s
which is a pointer to st
is uninitialized and hence contains garbage data. Now when you pass s
to createemptyStack
it tries to access memory location pointed by garbage data in s
leading to segmentation fault. You first need to allocate space for structure by either defining a struct object
st obj;
st* s = &obj;
or by dynamic memory allocation
s = malloc(sizeof(st))
s
is defined as a pointer to a stack object. You need an actual struct stack
object for s
to point to. Either define one as a local variable:
st obj;
st *s = &obj;
or allocate one from the heap:
st *s = malloc(sizeof(*s));
if (s == NULL) {
fprintf(stderr, "allocation failure\n");
exit(1);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.