The Muffin Boy
The Muffin Boy

Reputation: 314

Failing to implement a very simple stack array in C

#include <stdio.h>
#include <stdlib.h>
static int top = 0;
static char stack[100];    

void push(char thing2push)
{
if (top == 100){
    fprintf(stderr, "Too many things in the stack");        
    exit(1);
}else{  
    stack[top] = thing2push;
    top++;
    }
}

then in the main I have:

 extern void push(int);
 push(1);

but that results in "segmentation fault". My guess that it has something to do with memory violations, but I have no idea on how to fix it.

EDIT Here's the full code:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
extern int pop();
extern void push(int);

void readTag(){ 
    int tagVal = getchar();
    int poppedVal;
    if (getchar() == '/'){
            poppedVal = pop();
            if (poppedVal != tagVal){
                 printf("NOT Valid");
                 exit(1);
             }
    }else{
       push(1);
    }

}


 int main(int argc, char * argv[])
 {
      int ch;
      while ((ch = getchar()) != EOF) {
          if (!(isalpha(ch) || ch == '<'))
          continue;
          readTag();
       }
       printf("Valid");     
       exit(0);
 }

and here's the stack:

#include <stdio.h>
#include <stdlib.h>
static int top = 0;
static char stack[100];

int isEmpty()
{
        return !(top);
}

char pop()
{
        if (isEmpty()){
            fprintf(stderr, "Stack is empty");      
        exit(1);
    }   
    top--;
   return stack[top+1];
}

 void push(char thing2push)
 {
    if (top == 100){
           fprintf(stderr, "Too many things in the stack");     
        exit(1);
    }else{  
        stack[top] = thing2push;
        top++;
    }
}

Upvotes: 1

Views: 76

Answers (1)

barak manos
barak manos

Reputation: 30146

The top variable always indicates the next entry in the stack (which obviously does not contain a valid element, as far as your program concerns). So you're not supposed to read the value at stack[top].

The segmentation fault occurs in function pop, when top reaches 100:

top--;               // top == 99
return stack[top+1]; // return stack[100]

You should write into stack[top], but read from stack[top-1].

You can leave function push as is, and change only function pop:

top--;
return stack[top];

Upvotes: 1

Related Questions