简体   繁体   中英

Segmentation fault while implementing stack as an array

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?

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));

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM