Skip to content
Advertisement

C segmentation fault on linux with strncmp

This works (‘Y’ must be single quotes):

JavaScript

This gives segmentation fault:

JavaScript

strncmp must be going off the deep end but not sure why since I’m passing a casted toupper() as (char *). Without the casting, same error.

FYI user_input() is (N.B. vars are global):

JavaScript

Thank you.

Advertisement

Answer

The return value of toupper is another character, not a pointer to a string. So you are trying access memory address 131 which is why you are getting a segfault. Since you are only interested in the one character, you can replace your offending line with:

JavaScript

Notice that in the comparison Y is in single quotes which denotes you are dealing with a character value (as opposed to double quotes which denote a string value).

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement