2

I had written a program in C to implement a simple stack. But I am getting segmentation fault in my program and finding it hard to find out what is wrong. Can any one help,

   #include<stdio.h>
   #include<stdlib.h>
   struct stack_structure{
     int stack_array[10];
     int stack_pointer;
   };
   void push_into_stack(struct stack_structure *,int);
   int main(){
     int no = 8;
     struct stack_structure *st;
     st->stack_pointer = -1;
     push_into_stack(st,no);
     return 0;
   }
   void push_into_stack(struct stack_structure *s,int no){
     s -> stack_pointer++;
     s -> stack_array[s -> stack_pointer] = no;
   }

3 Answers 3

6
struct stack_structure *st;

This only creates a pointer to a struct stack_structure. It does not allocate memory for the struct stack_structure itself.

You can try with this:

struct stack_structure st;
st.stack_pointer = -1;
push_into_stack(&st,no);

The other option is to dynamically allocate (and free) that structure:

struct stack_structure *st = malloc(sizeof(struct stack_structure));
...
// when you're done with it
free(st);
Sign up to request clarification or add additional context in comments.

Comments

4

See these lines:

 struct stack_structure *st;
 st->stack_pointer = -1;

You've declared a pointer variable but then you're using it uninitialized. A pointer has to point at something, and this one doesn't have anything to point to. The simplest fix would be to change these lines to:

 struct stack_structure st1, *st=&st1;
 st->stack_pointer = -1;

2 Comments

What about passing this struct varible into push_into_stack() function. &st1 should be passed?
I kept the pointer variable st you had, but gave it something to point out, in order to minimize the changes needed to fix your code. Of course it's better not to even make a pointer variable if you don't need it and just use & when you need to take the address of the structure to pass it to another function.
0

You need to malloc some space for the structure:

struct stack_structure *st = malloc(sizeof(struct stack_structure));

Comments

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.