3 ms·
gcc and clang should warn about this: #include <stdint.h> void foo() { uint32_t foo = 1; foo <<= 32; } According to godbolt,
by 10000truths 5y ago
gcc and clang should warn about this:
#include <stdint.h>
void foo() {
uint32_t foo = 1;
foo <<= 32;
}
According to godbolt, the following warning is emitted for gcc:
warning: left shift count >= width of type [-Wshift-count-overflow]
And for clang:
warning: shift count >= width of type [-Wshift-count-overflow]
https://godbolt.org/z/ffccWexMP https://godbolt.org/z/ffccWexMP
- hcs 5y agoDifferent issue, that's shifting so far it would never fit. Here's an example with clang ubsan: https://godbolt.org/z/6Wvhn5rP9 https://godbolt.org/z/6Wvhn5rP9 Note that with foo = 0 there's no UB.
- kzrdude 5y agoThe problem in the article is something like this: int main() { unsigned char foo = 0x80; unsigned int x = foo << 24; } and with ubsan enabled it says /app/example.c:5:30: runtime error: left shift of 128 by 24 places cannot be represented in type 'int' SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /app/example.c:5:30 in What's non-obvious is also the rules around arithmetic. Types unsigned char and unsigned int are mentioned in my snippet but the arithmetic - the `<<` operator - performed using the type int.