user11195802
user11195802

Reputation:

Problem with pushing elements to the stack in c

I implemented a stack in C as follows. And the program is working fine for three pushes but when I try to push more than 3 elements the program executes and the result is printing out but then the error message displays saying that the program has stopped working
My code is as follows :

#include <stdio.h>
#include <stdlib.h>

#define MAX 50

//typedef char stackEntryType;
typedef enum{FALSE,TRUE} Boolean;

typedef struct stack{
int top;
int entry[MAX];
}stack;

void createStack(stack *s){
s->top=-1;
}

Boolean IsStackEmpty(const stack *s){
return(s->top==-1);
}

Boolean IsStackFull(const stack *s){
return(s->top==MAX-1);
}

void push(stack *s,int item){
    if(IsStackFull(s)){
        printf("Stack is full\n");
        exit(1);
    }else{
        s->entry[++s->top]=item;
        printf("%d pushed to stack\n",item);
    }
}

void pop(stack *s)
{
    int item;
    if(IsStackEmpty(s))
    {
        printf("Stack is empty\n");
        exit(1);
    }
    else{
        item=s->entry[s->top--];
        printf("%d popped from the stack",item);
    }
}

void main()
{
    stack *s;
    createStack(&s);
    push(&s,1);
    push(&s,2);
    push(&s,3);
    push(&s,4);
    pop(&s);
}

Can someone resolve this issue?

Upvotes: 0

Views: 117

Answers (2)

ralf htp
ralf htp

Reputation: 9432

Curiously you are smashing your machine's stack with your current code, when compiling it i got :

1 pushed to stack
2 pushed to stack
3 pushed to stack
4 pushed to stack
*** stack smashing detected ***: <unknown> terminated

4386427's answer is right, especially the point with the compiler warnings. Alternatively you can build your stack in the machine's heap (dynamic memory) with malloc() :

struct stack *s = malloc (sizeof (struct stack))

memory allocation in Stack and Heap

If you malloc the memory on the heap you have to change in main() all &s to s :

void main()
{

    struct stack *s = malloc(sizeof(struct stack));
    createStack(s);
    push(s,1);
    push(s,2);
    push(s,3);
    push(s,4);
    pop(s);
    free(s);  // release allocated memory
}

Upvotes: 2

4386427
4386427

Reputation: 44339

There is no stack allocated at all. This

void main()
{
    stack *s;

only gives you a stack-pointer.

Change it to

void main()
{
    stack s;

to get a stack-object.

Notice: Creating the stack as a local variable in main is fine as long as MAX is relative small. If you change MAX to a huge value (e.g. #define MAX 5000000) it is better to allocate memory using malloc. See answer from @ralfhtp.

BTW: Enable compiler warnings. You are passing a stack** to something expecting a stack* The compiler would have warned you and you could have found the bug rigth away.

Upvotes: 1

Related Questions