Home > Net >  code segmentation fault when assign value to struct variable
code segmentation fault when assign value to struct variable

Time:02-20

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

CodePudding user response:

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; 

second one creates a stack object on the stack.

  •  Tags:  
  • c
  • Related