strcmp giving segmentation fault

char *get;

The above statement defines get to be a pointer to a character. It can store the address of an object of type char, not a character itself. The problem is with both scanf and strcmp call. You need to define an array of characters to store the input string.

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

int main(void) {
    // assuming max string length 40
    // +1 for the terminating null byte added by scanf

    char get[40+1];

    // "%40s" means write at most 40 characters
    // into the buffer get and then add the null byte
    // at the end. This is to guard against buffer overrun by
    // scanf in case the input string is too large for get to store

    scanf("%40s", get);
    int k = strcmp("sachin", get);
    printf("%d", k);

    return 0;
}

Leave a Comment