-1

I'm new to c and am writing a switch function that whenever the passed in string is ), }, ], it returns false when the popped out expression isn't the matching open parentheses. (yes, it's the balanced parentheses problem...)

I can be sure that the segmentation fault only comes from this switch statement, and the code works perfectly fine without it.

my code is:


switch (expr[i]) 
        { 
        case ')': if (pop(&Stack) == '{' || pop(&Stack) =='[') { 
                  return 0;}
            break; 

        case '}': if (pop(&Stack) == '(' || pop(&Stack) =='[') {
                  return 0; }
            break; 

        case ']': if (pop(&Stack) == '{' || pop(&Stack) =='(') {
                  return 0; }
            break; 
        } 

It gives me "Segmentation fault: 11".

1 Answers1

2

I doubt the switch is causing the segfault. It is more likely to be the use of pop().

Is pop changing the stack? If so, pop is twice being evaluated in:

 case ')':
    if (pop(&Stack) == '{'  ||  pop(&Stack) =='[')

when the character is ) and the matching value popped is (.

To fix, restructure this area of code like this (depending on how pop interacts):

/*
 *  Have a peek at the top of stack without disrupting content
 */
char top_of_stack = pop (&Stack);
push (&Stack, top_of_stack); // put it back

switch (expr[i]) 
{ 
case ')':
     if (top_of_stack == '{' || top_of_stack == '[')
            return 0;
     break; 

case '}':
     if (top_of_stack == '(' || top_of_stack == '[')
            return 0;
     break; 

case ']':
     if (top_of_stack == '{' || top_of_stack == '(')
            return 0;
      break; 
}
wallyk
  • 56,922
  • 16
  • 83
  • 148