Menu

false positive on loops

2023-01-13
2023-01-13
  • Daniel Black

    Daniel Black - 2023-01-13

    $ bin/cppcheck /tmp/u.c
    Checking /tmp/u.c ...
    /tmp/u.c:38:13: warning: Uninitialized variable: weights [uninitvar]
    for (s= weights[w]; s ;)
    ^
    /tmp/u.c:26:35: note: Assuming condition is false
    for (s= strtok(weight, delim) ; s ; s= strtok(NULL, delim))
    ^
    /tmp/u.c:38:13: note: Uninitialized variable: weights
    for (s= weights[w];
    s ;)
    ^

    On strtok is false, dst->weight_length= 0 from the initialization and the
    second loop will fail on its initial condition. and the third inner loop
    never accesses weights[w].

    Note its the set_if_smaller macro that throws the ability of cppcheck to
    find this fault.

    u.c:

    include <stddef.h></stddef.h>

    include <stdlib.h></stdlib.h>

    include <stdio.h></stdio.h>

    include <string.h></string.h>

    define set_if_smaller(a,b) do { if ((a) > (b)) (a)=(b); } while(0)

    define MY_UCA_MAX_WEIGHT_SIZE 9

    define array_elements(A) ((int) (sizeof(A)/sizeof(A[0])))

    typedef struct t
    {
    int weight_length;
    int weight[4][MY_UCA_MAX_WEIGHT_SIZE];

    } d;

    static void
    parse_weights(d dst, int is_variable, char weight)
    {
    const char
    delim= " []";
    size_t w;
    char weights[64];
    char
    s;
    dst->weight_length= 0;
    *is_variable= 0;
    for (s= strtok(weight, delim) ; s ; s= strtok(NULL, delim))
    {
    if (dst->weight_length < array_elements(weights))
    weights[dst->weight_length]= s;
    dst->weight_length++;
    }

    set_if_smaller(dst->weight_length, MY_UCA_MAX_WEIGHT_SIZE-1);

    for (w= 0; w < dst->weight_length ; w++)
    {
    size_t partnum= 0;
    for (s= weights[w]; s ;)
    {
    char
    endptr;
    int part= (int) strtoul(s + 1, &endptr, 16);
    if (w == 0 && s[0] == '')
    is_variable= 1;
    if (part > 0xFFFF)
    fprintf(stderr, "Weight is too large: %X\n", (int) part);
    dst->weight[partnum][w]= (int) part;
    s= endptr;
    partnum++;
    }
    }
    }

     
  • CHR

    CHR - 2023-01-13

    I think this is related to https://trac.cppcheck.net/ticket/11075
    Also, please use code tags.

     

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.