Search code examples
cvalgrindbitwise-or

Invalid read when using bitwise or


By accident, I wrote

if (var < 0 | List == NULL) {
   ...
}

where var is an int and List a int* (array of ints).

I meant to write

if (var < 0 || List == NULL) {
   ...
} 

I know that

The operators |, &, and ~ act on individual bits in parallel. They can be used only on integer types. a | b does an independent OR operation of each bit of a with the corresponding bit of b to generate that bit of the result.

Quote from here.

What I don't understand is that valgrind (with option --leak-check=full) gave me the error Invalid read of size 8 in the first case and no error in the second case.

I think the data access to var and List is the very same in both cases.

What type is the result of List == NULL ?


Solution

  • "I think the data access to var and List is the very same in both cases."

    No, the difference is short-circuit evaluation. With logical OR, the expression List == NULL will not be evaluated when var < 0.

    But with bitwise-OR, you will evaluate List == NULL even when var < 0. Why that triggers an "Invalid read of size 8" is hard to say because you haven't shown enough of the code. But I suspect that List is not initialized when var < 0.