How do I detect undefined behavior in the example below?
#include <iostream>
#include <stream>
int main() {
std::cout << "Undefined: " << std::string().front() << std::endl;
return 0;
}
Compiled with clang++ -fsanitize=address,undefined -g -Wall -Wextra main.cc.
My expected output at either compile time or run time would be an error. Calling front() on an empty string is undefined behavior according to cplusplus.com. The actual output is Undefined:.
Questions
- Can I produce an error at compile or run time? If not, why can the compiler not detect this?
- If not, is there any tool that can detect this? For example, static analysis.
Versions used:
$ clang++ --version
Apple LLVM version 9.0.0 (clang-900.0.37)
Target: x86_64-apple-darwin17.0.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
$ /usr/local/Cellar/gcc/7.2.0/bin/g++-7 --version
g++-7 (Homebrew GCC 7.2.0) 7.2.0
[Copyright Notice]
Related, relevant questions:
- A C++ implementation that detects undefined behavior? (But I am interested in this particular undefined behavior.)