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;
}
1
  • struct stack *s; is a pointer to the struct stack, it is not initialized, you have to allocate memory to it. Commented Feb 19, 2022 at 18:57

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @pm100 this solution works. should I cast the return value of malloc struct stack *s = (struct stack *)malloc(sizeof(struct stack));
@Jignesh23 have fun reading this stackoverflow.com/questions/605845/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.