LEO NARDO
LEO NARDO

Reputation: 17

Logical error in push operation in stack

I am doing insert operation on stack as an array but my program is crashing on entering the first value.

typedef struct Stack
{
  int top;
  int elements[20];
}
stack;
stack *s;

void push(int x)
{
  s->top++;
  if(s->top<=19){
  s->elements[s->top]=x;}
  else
    puts("Overflow");
}

Upvotes: 1

Views: 80

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134276

As per your present code, it looks like you're using s uninitialized. Use of unitialized memory invokes undefined behaviour which in turn may cause segmentation fault.

For safeguard from unitisalized s , you may want to modify your code like

void push(int x)
{
  if (s)         //check if `s` has been initialized.
  {
      s->top++;
      if(s->top<=19)
      {
          s->elements[s->top]=x;
      }
      else
          puts("Overflow");
  }
  else
      //abort, return error or something similar
}

NOTE:

Apart from the issue in hand here, there is one more hidden issue which will come forth as soon as you fix this issue.

In your push() function, you're incrementing the top value unconditionally. That means, even if the stack is full, your top value will increase and later it will cause in errorneous calculations.

You have to move the stack top increment part also under the value range checking.

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 310910

It seems you simply defined a pointer of type struct Stack but not allocated the stack itself

stack *s;

Thus s is equal to NULL. At least you should allocate the stack itself. For example

stack *s;

//...
s = malloc( sizeof( struct Stack ) );

But in any case there is no any need to define a pointer. You could define the stack itself. For example

stack s;

Aldo you need to set an initial value of data member top. I think you could initialize it with -1.

Also function insert itself is invalid.

void push(int x)
{
  s->top++;
  if(s->top<=19){
  s->elements[s->top]=x;}
  else
    puts("Overflow");
}

Each time the function is called it increases data member top even if it points already beyond the array. The valid function could look like

void push(int x)
{
   if ( s->top + 1 < 20)
   {
      s->elements[++s->top] = x;
   }
   else
   [
       puts("Overflow");
   }
}

Upvotes: 1

Related Questions