0

I am learning Stack in C and try to implement stack using array in C. This code I am using from https://codewithharry.com/videos/data-structures-and-algorithms-in-hindi-24

I create struct stack below. In the main , I create a struct stack s and assign a value of 10. While executing the code, there is segmentation fault happened. I tried to lldb in VS code. it shows below error.

Please help me how to fix this code segmentation fault. What is the reason for segmentation fault?

Exception has occurred. EXC_BAD_ACCESS (code=1, address=0x25)

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

// creating stack
struct stack
{
    int size; //store the size of stack
    int top; //store index of top most element
    int *arr; //to hold the address of the array
};

// Check if stack is empty
int isEmpty(struct stack *ptr)
{
    if (ptr->top == -1){
        return 1;
    }
    else{
        return 0;
    }
}

int isFull(struct stack *ptr)
{
    if (ptr->top == ptr->size - 1)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

int main()
{
    struct stack *s;
    s->size = 10; // This line has exception occured with EXC_BAD_ACCESS (code=1, address=0x25)
    s->top = -1;
    s->arr = (int *)malloc(s->size * sizeof(int)); //reserve memory in heap
    
    // Check if stack is empty
    if(isEmpty(s)){
        printf("The stack is empty");
    }
    else{
        printf("The stack is not empty");
    }

    // Pushing an element manually
    s->arr[0] = 7;
    s->top++;
 
    // Check if stack is empty
    if(isEmpty(s)){
        printf("The stack is empty");
    }
    else{
        printf("The stack is not empty");
    }
 
    return 0;
}
user8811698
  • 118
  • 1
  • 7
  • `struct stack *s;` is a pointer to the `struct stack`, it is not initialized, you have to allocate memory to it. – petrch Feb 19 '22 at 18:57

1 Answers1

1

This is wrong

struct stack *s;
s->size = 10; 

s is a pointer to a stack. What stack object is it pointing at, none, hence the error. You have to create an stack and point at it, or use one directly.

struct stack *s = malloc(sizeof(struct stack));
s->size = 10; 

or

struct stack s;
s.size = 10; 

The second one creates a stack object on the stack.

Laurel
  • 5,965
  • 14
  • 31
  • 57
pm100
  • 48,078
  • 23
  • 82
  • 145
  • Thanks @pm100 this solution works. should I cast the return value of malloc `struct stack *s = (struct stack *)malloc(sizeof(struct stack));` – user8811698 Feb 19 '22 at 19:30
  • @Jignesh23 have fun reading this https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – pm100 Feb 19 '22 at 19:32