[cfe-dev] Inconsistent warnings with -Wundefined-reinterpret-cast

Michael Laß via cfe-dev cfe-dev at lists.llvm.org
Mon Feb 22 12:01:25 PST 2021


Hi all!

I stumbled across some C++ code today that uses reinterpret_cast to reshape a 1D array into a 2D array. I wondered if this is actually legal or if it would cause undefined behavior. There is an elaborate post on Stack Overflow [1] that argues in favor of this method, quoting sections of the C++ standard but other people disagree [2].

So I went ahead and tested different variants of such conversions with Clang’s -Wundefined-reinterpret-cast flag:

        https://godbolt.org/z/aE4fEM

The results can be summarized as:
1. Casting from int[4] to int(&)[2][2] or int(&)[][2] causes a warning
2. Casting from int(*)[4] to int(*)[2][2] or int(*)[][2] and _immediately_ dereferencing causes a warning
3. Casting from int(*)[4] to int(*)[2][2] or int(*)[][2] without immediate dereferencing seems fine
4. Casting from int[4] to int(*)[2] seems fine
5. Dereferencing those pointers from 3. and 4. afterwards also seems fine

This seems to be a bit inconsistent. From the results I assume that the cast itself is fine but dereferencing the casted pointer is undefined behavior. However, if those operations are split across multiple source code lines, there is no warning. Is this a bug or a natural limitation of the error checking within Clang?

Cheers,
Michael


[1] https://stackoverflow.com/a/15284276
[2] https://stackoverflow.com/q/44398700


More information about the cfe-dev mailing list