1
#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++;
    }
}
3
  • Please post complete, runnable example. Commented Mar 12, 2014 at 15:51
  • Your signatures of push don't match: void push(int); vs void push(char);. I'm not sure if that's what causes your problem, but it surely is not allowed. Commented Mar 12, 2014 at 16:20
  • what did the debugger say? Commented Mar 12, 2014 at 16:39

1 Answer 1

1

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];
Sign up to request clarification or add additional context in comments.

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.