Search code examples
cmemoryvalgrind

Use of uninitialised value of size 8 Valgrind


I'm getting

==56903== Use of uninitialised value of size 8
==56903==    at 0x1000361D1: checkMSB (in ./UnittestCSA)
==56903==    by 0x10003732A: S_derive_k1_k2 (in ./UnittestCSA)

Code is as follows:

int32_t checkMSB(uint8_t *pKey){
    int8_t msb = 0;
    int32_t ret = 0;
    msb = 1 << (8 - 1);
    /* Perform bitwise AND with msb and num */
    if(pKey[0] & msb){
        ret = 1;
    } else {
        ret = 0;
    }
    return ret;
}

Not sure what is causing the issue.

If this

#define BITS (sizeof(int8_t) * 8)

is changed to this

#define BITS (sizeof(int) * 8)

it doesn't complain. I have #include <stdint.h> header file.

UPDATE

uint8_t localK1[BLOCKSIZE];
for(index = 0; index < inputLen; index++){
    localK1[index] = pInputText[index];
}

result = checkMSB(localK1);

Solution

  • Your checkMSB function declares only two local variables and one function parameter. The variables both have initializers, and the parameter (a pointer) will receive a value as a result of the function call, supposing that a correct prototype for it is in scope at the point of the call. Thus, none of these is used uninitialized.

    The only other data that are used (not counting constants), are those pointed to by the argument, pKey. Of those, your code uses pKey[0]. That it is Valgrind reporting the issue supports the conclusion that that's the data it is complaining about: valgrind's default memcheck service watches dynamically allocated memory, and that's the only thing involved that might be dynamically allocated.

    That the error disappears when you change the definition of BITS could be explained by the expression pKey[0] & msb being optimized away when BITS evaluates to a value larger than 8.

    As far as your update, which purports to show that the function's argument in fact points to initialized data, I'm inclined to think that you're looking in the wrong place, or else in the right place but at the wrong code. That is, there probably is either a different call to checkMSB that causes Valgrind to complain, or else the binary being tested was built from a different version of the code. I'm not prepared to believe that everything you've presented in the question is true, or at least not that it fits together the way you seem to be saying it does.