[Solved] Segmentation Fault in Simple C Calculator


You’re declaring a number of int* variables, but never allocating any memory for them. They should be int instead, since they contain indexes into the stack.

int valueTop = 0;
int operandTop = 0;

Then you should use these variables, you don’t need to dereference them. But when you pass them to functions that need to update the variables, you have to pass the address of the variable.

int main(int argc, char *argv[]){
    char *token;
    int tokenNumber = 1;
    int value[51];
    int valueTop = 0;
    int valueOne,valueTwo;
    char *operand[51];
    int operandTop = 0;
    char *operandOne;

    token = argv[tokenNumber];
    while (token != NULL){
        if (*token == '+' || *token == 'x' || *token == '['){
            pushOpStack(operand, &operandTop, token);
        }
        else if (*token == ']'){
            while (*operand[operandTop] != '['){
                operandOne = popOpStack(operand, &operandTop);
                if (*operandOne == '+'){
                    valueOne = popValStack(value, &valueTop);
                    valueTwo = popValStack(value, &valueTop);
                    pushValStack(value, &valueTop, valueOne + valueTwo);
                }
                if (*operandOne == 'x'){
                    valueOne = popValStack(value, &valueTop);
                    valueTwo = popValStack(value, &valueTop);
                    pushValStack(value, &valueTop, valueOne * valueTwo);
                }
            }
        }
        else {
            pushValStack(value, &valueTop, atoi(token));
        }
        tokenNumber++;
        token = argv[tokenNumber];
    }
    while (operandTop != 0){
        operandOne = popOpStack(operand, &operandTop);
        if (*operandOne == '+'){
            valueOne = popValStack(value, &valueTop);
            valueTwo = popValStack(value, &valueTop);
            pushValStack(value, &valueTop, valueOne + valueTwo);
        }
        if (*operandOne == 'x'){
            valueOne = popValStack(value, &valueTop);
            valueTwo = popValStack(value, &valueTop);
            pushValStack(value, &valueTop, valueOne * valueTwo);
        }
    }
    printf("\n%d",popValStack(value, &valueTop));
}

solved Segmentation Fault in Simple C Calculator