Skip to content
Advertisement

C segmentation fault on linux with strncmp

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

if (toupper(user_input(2)) == 'Y') printf("you said y");

This gives segmentation fault:

if (!strncmp((char *)toupper(user_input(2)), "Y", 1)) printf("you said y");

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):

char* user_input(int size) { //size is the number of characters to capture. Remember to account for n or 
    if (fgets(buf, size, stdin) != NULL) { //buf is char buf[1000];
        if ((p = strchr(buf, 'n')) != NULL) //Check if carriage return in string
            *p = ''; //Replace carriage return with NULL
        p = buf; //Set pointer back to input for others to access
        return *p;
   } else {
       p = buf;
       p[0] = "";
       return ""; //Return NULL if input fails
   }
}

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:

if (toupper(user_input(2)) == 'Y') {
   printf("You said yesn");
}

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