Search code examples
cmisra

MISRA C 2012 violation of rule 9.1 even with an initialized variable


I am trying to get rid of violation rule 9.1 from my code.

Rule 9.1: The value of an object with automatic storage duration shall not be read before it has been set

Sample code:

#include <stdint.h>
#include <stdbool.h>
#define VAL 0xABCDEFABU

int32_t main(void);
static int32_t do_test(bool k);
static void func(uint64_t *var3, const uint64_t *var5);

int32_t 
main (void)
{
    bool b = false;

    int32_t y = do_test(b);

    return y;
}

static int32_t
do_test(bool k)
{
    uint64_t i = 0, var4[10];

    int32_t result = 0;

    for(i = 0U; i < 10U; i++) {
      var4[i] = VAL + i;
    }

    if(k == false) {
      uint64_t var2[10];
      func(var2, var4);

      if(var2[9] == var4[9]) {
        result = 1;
      }

    }

      return result;
}


static void
func(uint64_t *var3, const uint64_t *var5)
{
    int32_t i;
    for(i = 0; i < 10; i++) {
      var3[i] = var5[i];
    }

}

I am initializing var2 in the function do_test by calling another function "func" where var4 is copied to var2.

It is compiling fine and I am getting y value = 1.

Is it the violation due to parameters in func as pointers and the function do_test is not getting aware about the value assignment through pointers in func

Is there anyway to fix this issue ?


Solution

  • This is a common tool bug in many static analysers. Your static analyser can apparently not understand that the function func initializes all the items of var2, and therefore you get the false positive on the line var2[9] == var4[9].

    On many static analysers, code such as int my_array[10]; initialize(my_array); gives frustrating false positives. "You try to initialize the array before it has been initialized!!!" Oh really... thank you, most helpful static analyser.

    Your code is fine. File a bug report with your tool vendor.