Menu

False positive negativeIndex (array access out of bounds)

Guillaume
2022-05-31
2022-07-05
  • Guillaume

    Guillaume - 2022-05-31

    Hi,

    I get an array out of bounds false positive with these nested for loops:

    #define NULL ((void*)0)
    
    #define LIST_SIZE 1
    static void* list[LIST_SIZE];
    
    void unregister_ptr(void *ptr)
    {
            int i;  // index of "ptr" in "list"
            int j;  // index of the last non-null element in "list"
    
            // Remove "ptr" from "list"
            for (i=0; i<LIST_SIZE; i++) {
                    if (list[i] == ptr) {
                            for (j=i; j<LIST_SIZE-1; j++) {
                                    if (list[j+1] == NULL) {
                                            break;
                                    }
                            }
                            /* Replace the "ptr" entry with the last non-null "list" entry, and set
                             * this last non-null entry (which might by the "ptr" entry) to NULL */
                            list[i] = list[j];
                            list[j] = NULL;
    
                            return;
                    }
            }
    }
    

    cppcheck --verbose sample.c

    Checking sample.c ...
    Defines:
    Undefines:
    Includes:
    Platform:Native
    sample.c:21:18: error: Array 'list[1]' accessed at index -1, which is out of bounds. [negativeIndex]
       list[i] = list[j];
                     ^
    sample.c:14:15: note: Assuming that condition 'j<1-1' is not redundant
       for (j=i; j<LIST_SIZE-1; j++) {
                  ^
    sample.c:21:18: note: Negative array index
       list[i] = list[j];
                     ^
    sample.c:22:8: error: Array 'list[1]' accessed at index -1, which is out of bounds. [negativeIndex]
       list[j] = NULL;
           ^
    sample.c:14:15: note: Assuming that condition 'j<1-1' is not redundant
       for (j=i; j<LIST_SIZE-1; j++) {
                  ^
    sample.c:22:8: note: Negative array index
       list[j] = NULL;
           ^
    

    Tested on cppcheck v2.7, v2.8 and the current git master branch.
    Attached file is the output of cppcheck from git master branch, with the --debug flag.

    Thank you very much for you work on cppcheck !

     
  • CHR

    CHR - 2022-05-31

    Thanks for reporting, ticket is here: https://trac.cppcheck.net/ticket/11113

     
  • Guillaume

    Guillaume - 2022-06-01

    Thanks !

     
  • T Tanner

    T Tanner - 2022-07-05

    Did you try using unsigned integers for i and j? It might fix this (asking because I'm aware of various static checkers that will produce warnings when you use a signed integer for an array index)

     

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.