Menu

NULL parameter to strcmp will cause seg fault

2024-02-26
2024-02-27
  • Luis Cortes

    Luis Cortes - 2024-02-26

    This code will seg fault on Redhat linux under gcc. The problem is the strcmp does not like NULL parameters. I can't seem to just run a scanner like cppcheck, flawfinder, semgrep, etc and find this issue. Is there something I might be missing or do I have to write a custom rule for this?

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    char* greeting(int value)
    {
        switch (value) {
            case 1:
                return strdup("hello");
            case 2:
                return strdup("hola");
            case 3:
                return strdup("bon jour");
            default:
                return NULL;
        }
        return NULL;
    }
    
    
    int main() 
    {
        int value = 0;
        printf("Enter a value: ");
        scanf("%d", &value);
        printf("Value is: %d\n", value);
    
        char *p = greeting(value);
    
        printf("Greeting: %s\n", p);
        printf("Equal to hello %d\n", (strcmp(p, "hello") == 0));
    
        free(p);
    }
    
     
  • Daniel Marjamäki

    The problem is the strcmp does not like NULL parameters.

    Cppcheck knows this. You get a warning if the null pointer is passed more directly to the function.

    By intention, Cppcheck does not guess what values output parameters get when for instance scanf is called. If we can determine what the value is that is fine but in general we don't want to make stupid random guesses. There is this related trac ticket:
    https://trac.cppcheck.net/ticket/8236

    I think that "always guess that all external functions can return any value and write any value in their output parameters" would be very noisy.. however I believe that is what i.e. CERT recommends.. I would say your example violates EXP34-C:
    https://wiki.sei.cmu.edu/confluence/display/c/EXP34-C.+Do+not+dereference+null+pointers
    Cppcheck Premium has CERT checking however Cppcheck Premium does not warn yet about your example code; I believe we should make sure it does..

    do I have to write a custom rule for this?

    imho I would not write some custom rule.

     

    Last edit: Daniel Marjamäki 2024-02-27

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.