M.Elsayed
M.Elsayed

Reputation: 85

Why is strlen causing a segmentation fault in C?

(Warning) Yes this is a part of an assignment I am working on, but I am completely desperate at this point and NO I am not looking for you guys to solve it for me, but any hint would be much appreciated!(/Warning)

I am pretty much trying to make an interactive menu, the user is meant to input an expression (For example "5 3 +") and the program should detect that it's in postfix notation, unfortunately I have been getting segmentation fault errors and I suspect they have something to do with the use of the strlen function.

EDIT: I was able to make it work, first the char expression[25] = {NULL}; line
becomes char expression[25] = {'\0'};

And when calling the determine_notation function I removed the [25] from the array I am passing like so: determine_notation(expression, expr_length);

Also the input[length] part I changed to input[length-2] since like mentioned in a previous comment, input[length] == '\0' and input[length--] == '\n'.

All in all thanks for all the help!

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int determine_notation(char input[25], int length);

int main(void)
{
    char expression[25] = {NULL}; // Initializing character array to NULL
    int notation;
    int expr_length;

    printf("Please enter your expression to detect and convert it's notation: ");
    fgets( expression, 25, stdin );

    expr_length = strlen(expression[25]); // Determining size of array input until the NULL terminator
    notation = determine_notation( expression[25], expr_length ); 
    printf("%d\n", notation);
}

int determine_notation(char input[25], int length) // Determines notation
{

    if(isdigit(input[0]) == 0)
    {
        printf("This is a prefix expression\n");
        return 0;
    }
    else if(isdigit(input[length]) == 0)
    {
        printf("This is a postfix expression\n");
        return 1;
    }
    else
    {
        printf("This is an infix expression\n");
        return 2;
    }
}

Upvotes: 0

Views: 3212

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

You probably got a warning explaining that you are converting a char to a pointer in this call:

expr_length = strlen(expression[25]);
//                             ^^^^

This is the problem - your code is referencing a non-existent element past the end of the array (an undefined behavior) and tries to pass it to strlen.

Since strlen takes a pointer to the beginning of the string, the call needs to be

expr_length = strlen(expression); // Determining size of array input until the NULL terminator

Upvotes: 5

Related Questions