Menu

False positive for style: 'unreadVariable' in some cases when a reference is used

ramonunch
2023-07-05
2023-07-06
  • ramonunch

    ramonunch - 2023-07-05

    I encountered this problem with a code that I simplified a first time to the following (kinda close to what I was actually doing):

    void funk(char *str, bool ignorestr)
    {
        char buf[32], *p=buf;
    
        if (ignorestr)
            buf[0] = '\0'; // style: Variable 'buf[0]' is assigned a value that is never used. [unreadVariable]
        else
            p = str;
    
        puts(p); // but p can point to buf!
    }
    

    Then I thought a bit more and simplified even more the problem like this: and with the following code I still get the unreadVariable style warning using the latest 2.11 release

    void f(void)
    {
        int x[1], *p = x;
        x[0] = 42; // style: Variable 'x[0]' is assigned a value that is never used. [unreadVariable]
    
        g(p);
    }
    

    However when I use a simple int for x I get no error ie:

    void f2(void)
    {
        int x, *p = &x;
        x = 42;
    
        g(p);
    }
    

    No warnings here...

    So I thought here is a problem with implicit casting from int[N] to int* but using int *p=&x[0] does not fix the warning. Of course avoiding the warning is easy and could help clarifying the code (what I did) but it is still a false positive.

     
    • CHR

      CHR - 2023-07-06
       
      👍
      1
  • Sylvain Joubert

    Sylvain Joubert - 2023-07-06

    I also encountered a FP using reference. Not sure if it's the exact same pattern though:

    #include <nlohmann/json.hpp>
    
    bool check();
    bool double_check();
    
    nlohmann::json test()
    {
      nlohmann::json data;
      auto& elem = data["elem"]; // style: Variable 'elem' is assigned a value that is never used. [unreadVariable]
    
      if (check())
      {
        elem = 42;
      }
      else if (double_check())
      {
        elem = 1;
      }
    
      return data;
    }
    

    Notes:
    * I could not easily reduce/reproduce this without using nlohmann::json, so I don't know if this is actually a FP or a missing "library" configuration for this type.
    * If I change the else if into an else the warning disappears

     
    • CHR

      CHR - 2023-07-06

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

       
      👍
      2

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.