https://gcc.gnu.org/bugzilla/show_bug.cgi?id=65049
Bug ID: 65049 Summary: Undefined behaviour with std::char_traits<char> Product: gcc Version: 5.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: libstdc++ Assignee: unassigned at gcc dot gnu.org Reporter: redi at gcc dot gnu.org #include <string> int main() { const char* p = 0; char* q = 0; std::char_traits<char>::compare(p, q, 0); std::char_traits<char>::find(p, 0, '0'); std::char_traits<char>::move(q, p, 0); std::char_traits<char>::copy(q, p, 0); std::char_traits<char>::assign(q, 0, '0'); } Compiled with ubsan: /home/jwakely/gcc/5/include/c++/5.0.0/bits/char_traits.h:259:48: runtime error: null pointer passed as argument 1, which is declared to never be null /home/jwakely/gcc/5/include/c++/5.0.0/bits/char_traits.h:259:48: runtime error: null pointer passed as argument 2, which is declared to never be null /home/jwakely/gcc/5/include/c++/5.0.0/bits/char_traits.h:267:77: runtime error: null pointer passed as argument 1, which is declared to never be null /home/jwakely/gcc/5/include/c++/5.0.0/bits/char_traits.h:271:74: runtime error: null pointer passed as argument 1, which is declared to never be null /home/jwakely/gcc/5/include/c++/5.0.0/bits/char_traits.h:271:74: runtime error: null pointer passed as argument 2, which is declared to never be null /home/jwakely/gcc/5/include/c++/5.0.0/bits/char_traits.h:275:73: runtime error: null pointer passed as argument 1, which is declared to never be null /home/jwakely/gcc/5/include/c++/5.0.0/bits/char_traits.h:275:73: runtime error: null pointer passed as argument 2, which is declared to never be null /home/jwakely/gcc/5/include/c++/5.0.0/bits/char_traits.h:279:71: runtime error: null pointer passed as argument 1, which is declared to never be null We need to check for __n > 0 here: static int compare(const char_type* __s1, const char_type* __s2, size_t __n) { return __builtin_memcmp(__s1, __s2, __n); } Similarly for find, move, copy, assign. This is a real problem, GCC 4.9+ will optimize away null checks based on calls to these functions.