Menu

False positive Condition 'addcnt!=255' is always true (uint8_t addcnt is decremented).

2025-03-22
2025-03-23
  • Mario De Weerd

    Mario De Weerd - 2025-03-22
    #include <stdint.h>
    #include <stdio.h>
    #include <string.h>
    char test[50];
    static void test_255match()
        {
        uint8_t addcnt;
        for (addcnt = 0; addcnt < 10; addcnt++)
            {
            printf("%u\n", addcnt);
            if (test[addcnt] == '+')
                {
                test[addcnt] = 0;
                addcnt--;
                printf("AFTER: %u\n", addcnt);
                if (addcnt != 255)
                    {
                    printf("CONDITION MATCHED:%u\n", addcnt);
                    }
                else
                    {
                    printf("CONDITION NOT MATCHED:%u\n", addcnt);
                    }
                }
            }
        }
    
    void main()
        {
        snprintf(test, sizeof(test), "A+CD");
        test_255match();
        snprintf(test, sizeof(test), "+BCD");
        test_255match();
        }
    
    /*
     * With this testcase file called 'und.c':
     *
     * cppcheck --enable=style,portability,warning,performance,unusedFunction und.c
     * yields:
     * und.c:16:24: style: Condition 'addcnt!=255' is always true [knownConditionTrueFalse]
     *             if (addcnt != 255)
     *                        ^
     * und.c:14:13: note: addcnt is decremented', new value is 254
     *             addcnt--;
     *             ^
     * und.c:16:24: note: Condition 'addcnt!=255' is always true
     *             if (addcnt != 255)
     *                        ^
     *
     *
     * Demonstration that this is false positive:
     *
     * `gcc und.c ; ./a.exe` yields message "CONDITION MATCHED":
     *
     * 0
     * 1
     * AFTER: 0
     * CONDITION MATCHED:0
     * 1
     * 2
     * 3
     * 4
     * 5
     * 6
     * 7
     * 8
     * 9
     * 0
     * AFTER: 255
     * CONDITION NOT MATCHED:255
     * 0
     * 1
     * 2
     * 3
     * 4
     * 5
     * 6
     * 7
     * 8
     * 9
     */
    
     

    Last edit: Mario De Weerd 2025-03-22
  • CHR

    CHR - 2025-03-23
     

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.