Is it legal to define global variable named "read" in C++?

Revision en2, by yeputons, 2021-10-03 14:25:53

I've bumped into this blog post by imtiyazrasool92 (unfortunately, it's already deleted). They've found out that simply declaring a global variable called read makes your program behave strangely on Codeforces: the outcome of 130645378 is RUNTIME_ERROR, Exit code is 2147483647, and here is the code:

#include <iostream>
int read;
int main(){
    std::ios_base::sync_with_stdio(false);
    std::cin >> read;
}

I was unable to minimize the example any further.

The original post was even more interesting: 130642683 is Accepted, but 130643108 is Runtime Error all of a sudden.

The compiler on Codeforces is G++17 9.2.0 (64 bit, msys2). However, I was able to reproduce the issue both on my local machine (g++ (Rev2, Built by MSYS2 project) 10.3.0) and the latest GCC on Godbolt as long as the -static key is used for compilation just like on Codeforces. Clang is also affected.

It looks like the read variable here replaces the standard Linux read function (which is emulated by msys2). Here is a symmetrical example:

#include <iostream>
int write;
int main(){
    std::ios_base::sync_with_stdio(false);
    std::cout << 10;
}

And here is one more (130646314), although now I at least get some warnings:

int malloc;
int main(){
}
a.cpp:1:5: warning: built-in function 'malloc' declared as non-function [-Wbuiltin-declaration-mismatch]
    1 | int malloc;
      |     ^~~~~~

My understanding is that all these examples invoke ODR violation, which makes the program ill-formed (invalid) without any requirements on the compiler to emit the error. However, I am not sure, so I asked on StackOverflow.

Any other ideas?

Tags gcc, global variable, read, runtime error, mysterious runtime error

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en4 English yeputons 2021-10-03 14:40:04 4 Tiny change: 'on:130645378] is `RUNT' -> 'on:130645392] is `RUNT'
en3 English yeputons 2021-10-03 14:37:59 17 Tiny change: 'dy deleted). They've' -> 'dy deleted due to downvotes). They've'
en2 English yeputons 2021-10-03 14:25:53 145
en1 English yeputons 2021-10-03 14:23:49 2009 Initial revision (published)