Search code examples
crpn

How to fix Segmentation Fault while trying to do RPN in C


I am trying to make a program that will use RPN, which will calculate a series of integers. I have some standard functions (pop, push) that I can't change. But when I run the below code, I get a segmentation fault.

Since I can't change the inside core of those two functions, so I tried to change the way that I am calling them (I made stack[] a dynamic array and the top an int pointer) but nothing changes.

#include <stdio.h>
#include <stdlib.h>
#define N 1000

void push(int stack[],int *t,int obj)
{
    if((*t)==(N-1))
    {
        printf("Stack overflow...\n");
        getchar(); //getc
        abort();
    }
    else
        stack[++(*t)]=obj;
}

int pop(int stack[],int *t)
{
    int r;
    if((*t<0))
    {
        printf("Stack empty...\n");
        printf("Error in expresion.\n");
        getchar(); //getc
        abort();           
    }
    else
        r=stack[(*t)--];
    return(r);
}

int isdigit(char in)
{
    int flag;

    if (in>=48 && in<=57)  //if its terminus 
        flag=1;
    else if(in==42 || in==43 || in==45 || in==47) //if its  operator
        flag=2;
    else 
        flag=0;

    return flag;
}

int main(int argc, char** argv) {

    int *stack=(int*) malloc(N*sizeof(int));
    char input;
    int i=0,*top=0,flag;
    int num1,num2;
    float result;

    if (stack == NULL) {
        printf("Out of memory!\n");
        return (1);
    }  
    printf("Give the Formula: ");
    while(input=getchar())
    {
        flag=isdigit(input);
        if(flag==1) //if its terminus 
        {
            push(&stack[i],top,input);
        }
        if(flag==2) //if its enforcer
        {
            num1=pop(&stack[i],top);
            num2=pop(&stack[i+1],top);
            if (input==42)   //case of +
                result=num1+num2;
            if (input==43) //case of *
                result=num1*num2;
            if (input==45) //case of -
                result=num2-num1;

            if (input==47) //case of /
                if(num2!=0) 
                    result=num2/num1;
                else
                    printf("Can't do the operation");
            push(&stack[i],top,result);
        }
        if(flag==0)  //case of everything else
        {
            printf("Error");
            exit(1);
        }
        printf("Operand: %c\n",input);
        //  for(int j=0;j<strlen(stack);j++)
        //   printf("stack[%d]=%d\n",i,stack[j]);
        //printf current status of stack

        i++;
    }   
    return (EXIT_SUCCESS);
}

If you have a series of integers like 234+*, the stack should be firstly 2,3,4,+,*, secondly 5,4,*, thirdly 20.


Solution

  • In main you defined top as pointer and initialized it to point to null.

    After that, in push, you try to dereference the null location via *t. Here you get segmentation fault.