Home > Back-end >  Segmentation fault while implementing stack as an array
Segmentation fault while implementing stack as an array

Time:10-16

This is a menu-driven program that carries out basic stack operations using arrays in the C programming language. The functions that are performed are push, pop, peep,isempty and isfull.

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


struct stack
{
    long int top;
    long int size;
    char* key;
};


int is_empty(struct stack *s)  //check if its empty
{
    if(s->top==-1)
    {
            return -1;
    }
    else
    {
        return 1;
    }
}
int is_full(struct stack *s)  //check if its full
{
    if (s->top ==s->size-1)
    {
        return -1;
    }
    else
    {
        return 1;
    }
}


void push(struct stack *s, char x)  //pushes into stack
{
int check;
check = is_full(s);
if(check==-1)
{
    printf("-1\n");
   
}
else
{
s->top = s->top 1;
s->key[s->top]=x;
}
}

 
void pop(struct stack *s)   //deletes the last element
{
int check;
check = is_empty(s);
if(check==-1)
{
    printf("-1\n");
    
    
}
else
{
char k;
k = s->key[s->top];
printf("%c\n",k);
s->top--;
}
}

void peep(struct stack *s)  //prints the last element without deleting
{   int check;
char k;
    check = is_empty(s);
    if (check == -1)
    {
        printf("-1\n");
    }
    else
    {
            k = s->key[s->top];
           printf("%c \n",k);
    }    
}

int main()
{


    char ch;
    char x;
    long int n;
    struct stack *s;
    scanf("%ld ", &n);
    s->size = n;  //initialise the size 
    s->top = -1;  //setting as -1 base case
    s->key= (char *)malloc(n*sizeof(char));  //dynamic allocation of keys
    while(1)
    {
        scanf("%c ",&ch);
        switch(ch)
        {
        case 'i':
                scanf("%c ",&x);
                push(s,x);
                break;
        case 'd':pop(s);
                break;
        case 'p':peep(s);
                break;
        case 't':exit(0); //termination case
    }  
}
return 0;
}

This is a C program that is working for me in some online compilers but in VScode and other compilers, it's showing a segmentation fault without any output. This is an implementation of stack using arrays. Is it a problem with any of the scanf functions?

CodePudding user response:

You have created a pointer variable s and then access the size field on that struct.

    struct stack *s;
    scanf("%ld ", &n);
    s->size = n;  //initialise the size

Except s doesn't actually point to anything at this point. You need to either statically or dynamically allocate memory for that struct.

struct stack s;

Or:

struct stack *s = malloc(sizeof(struct stack));
  • Related