Menu

FP: for loop ignores condition

2020-05-06
2020-05-06
  • Jochen Karrer

    Jochen Karrer - 2020-05-06

    In the for loop cppcheck-1.90 ignores the abort condition or the pre-initialization of a variable and generates a false positive warning:

    #include <stdlib.h>
    
    typedef struct ListEntry {
        struct ListEntry *next;
    } ListEntry;
    
    static ListEntry *listHead = NULL;
    
    static void
    InsertListEntry(ListEntry * newEntry)
     {   
        ListEntry *cursor, *prev;
        for (prev = NULL, cursor = listHead; cursor != NULL; prev = cursor, cursor = cursor->next) {
            /* Compare something and break */
        }   
        if (prev) {
            /* insert to middle of list */ 
        } else {
            /* This is a new list head */ 
        }   
    }
    

    Checking listEntry.c ...
    listEntry.c:13:82: warning: Either the condition 'if(prev)' is redundant or there is possible null pointer dereference: cursor. [nullPointerRedundantCheck]
    for (prev = NULL, cursor = listHead; cursor != NULL; prev = cursor, cursor = cursor->next) {
    ^
    listEntry.c:16:8: note: Assuming that condition 'if(prev)' is not redundant
    if (prev) {
    ^
    listEntry.c:13:65: note: Assignment from 'cursor'
    for (prev = NULL, cursor = listHead; cursor != NULL; prev = cursor, cursor = cursor->next) {
    ^
    listEntry.c:13:82: note: Null pointer dereference
    for (prev = NULL, cursor = listHead; cursor != NULL; prev = cursor, cursor = cursor->next) {

     

    Last edit: Jochen Karrer 2020-05-06
  • Daniel Marjamäki

    Thanks! I can reproduce with cppcheck HEAD. It's somehow related to our data flow analysis. I created this ticket: https://trac.cppcheck.net/ticket/9701

     

    Last edit: Daniel Marjamäki 2020-05-06

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.