https://gcc.gnu.org/bugzilla/show_bug.cgi?id=101850
Bug ID: 101850 Summary: Initialising a std::string variable to itself does not fail at compile time, but throws std::bad_alloc at run time Product: gcc Version: 8.4.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: c++ Assignee: unassigned at gcc dot gnu.org Reporter: prasantabehera at hotmail dot com Target Milestone: --- Version info: ============= ~$ g++ --version g++ (Ubuntu 8.4.0-1ubuntu1~18.04) 8.4.0 Copyright (C) 2018 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ~$ gcc --version gcc (Ubuntu 8.4.0-1ubuntu1~18.04) 8.4.0 Copyright (C) 2018 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Sample Program: =============== ~$ cat t.cpp #include <string> int main() { std::string s = s; return 0; } Problem Description: ==================== The above program tries to initialise a string with itself which is wrong! However g++ does not show any compile time error, but the resulting binary fails at run time throwing std::bad_alloc as shown below. ~$ g++ t.cpp ~$ ./a.out terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc Aborted (core dumped) gcc however shows a link time error which is slightly better. ~$ gcc t.cpp /tmp/cc30YkgH.o: In function `main': t.cpp:(.text+0x27): undefined reference to `std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)' t.cpp:(.text+0x38): undefined reference to `std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()' collect2: error: ld returned 1 exit status I think the coding error should be caught at the compile time by g++. Also, the problem is same with any generic C++ class/struct: #include <string> struct M { std::string s; }; int main() { // std::string s = s; M m = m; return 0; } Also checked with g++ version 7.5.0, to see the same behavior.