Menu

false positive - invalidFunctionArg (not all if:s are checked)

2020-10-03
2021-01-29
  • Henrik Holst

    Henrik Holst - 2020-10-03

    Now this code could be written better (and I will after posting this), but it did expose a false positive in cppcheck (tested with v2.2):

            size_t added_len = message->data_used - oldpos;
    
            if (added_len < 50) { /* line 1186 */
                added_len = 50 - added_len; /* line 1187 */
    
                if (added_len > 6) { /* this if is ignored by cppcheck */
                    added_len -= 5; /* line 1190 */
                    add_tag (message, tag, oldpos, message->data_used - oldpos);
                    add_tag (message, 0xffffffff, message->data_used, added_len);
    
                    grow_buffer (message, added_len);
    
                    message->data[message->data_used++] = 241;
                    added_len--; /* line 1197 */
    
                    memset (message->data + message->data_used, ' ', added_len - 1); /* lin e 1199 */
                    message->data_used += added_len;
                    message->data[message->data_used - 1] = '\0';
                    return 1;
                }
            }
    

    This yields this error from cppcheck:

    src/encode.c:1199:64: warning: Either the condition 'added_len<50' is redundant or memset() argument nr 3 can have invalid value. The value is -6 but the valid values are '0:'. [invalidFunctionArg]
        memset (message->data + message->data_used, ' ', added_len - 1);
                                                                   ^
    src/encode.c:1186:17: note: Assuming that condition 'added_len<50' is not redundant
      if (added_len < 50) {
                    ^
    src/encode.c:1187:19: note: Assignment 'added_len=50-added_len', assigned value is 1
       added_len = 50 - added_len;
                      ^
    src/encode.c:1190:5: note: Compound assignment '-=', assigned value is -4
        added_len -= 5;
        ^
    src/encode.c:1197:5: note: added_len is decremented', new value is -5
        added_len--;
        ^
    src/encode.c:1199:64: note: Invalid argument
        memset (message->data + message->data_used, ' ', added_len - 1);
    

    So cppcheck checks the if at line 1187 but ignores the one at line 1189 that makes sure that the variable is > 6 which makes cppcheck assume that the variable can be 1 when it cannot.

     
  • CHR

    CHR - 2021-01-25

    After surrounding the code with int main() {...}, I get the same warnings in v2.3.

     
  • CHR

    CHR - 2021-01-29

    This is fixed in head.

     
  • Henrik Holst

    Henrik Holst - 2021-01-29

    Great thanks!

     

Log in to post a comment.