使用C++模块分区与实现单元时程序崩溃问题排查
问题:C++模块使用中std::string触发崩溃,是使用错误还是编译器问题?
程序代码
主程序代码
#include <cstdio> import animal; int main() { auto s = makeSound(); printf("%s", s.c_str()); return 0; }
模块接口代码
module; #include <string> export module animal; import :sound; export std::string makeSound() { return makeSound_Impl(); }
模块实现单元代码
module; #include <string> module animal:sound; std::string makeSound_Impl() { return "Wroooarrh"; }
编译命令
g++ -fmodules-ts -g -std=c++20 animal_sound.cpp -c -o animal_sound.o g++ -fmodules-ts -g -std=c++20 animal.cpp -c -o animal.o g++ -fmodules-ts -g -std=c++20 animal.o animal_sound.o main.cpp -o main.exe
编译器版本
g++ --version g++ (Ubuntu 13.1.0-8ubuntu1~22.04) 13.1
崩溃错误信息
Program received signal SIGSEGV, Segmentation fault. 0x00005555555566c2 in std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::_M_data (this=0xd00aa32b9e55bf00) at /usr/include/c++/13/bits/basic_string.h:223 223 { return _M_dataplus._M_p; } (gdb) bt #0 0x00005555555566c2 in std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::_M_data (this=0x0) at /usr/include/c++/13/bits/basic_string.h:223 #1 0x0000555555556f3a in std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::c_str (this=0x7fffffffda50) at /usr/include/c++/13/bits/basic_string.h:2584 #2 0x0000555555556ea6 in main () at main.cpp:7
正常运行的代码版本
当直接在animal模块中定义makeSound(不通过实现单元代理)时,程序运行正常:
module; #include <string> export module animal; export std::string makeSound() { return "Sound!"; }
补充测试结果
编辑1
无需实现单元也能复现问题:若animal模块中不包含#include <string>,问题就会消失。
子模块代码:
module; #include <string> export module animal:sound; export std::string makeSound() { return "Wroooarrh"; }
主模块代码:
module; // #include <string> // 添加该头文件会导致程序崩溃 export module animal; export import :sound;
编辑2
已在GCC官方Bug提交平台上报该问题。
结论
这是GCC编译器的问题,并非代码使用错误。
内容的提问来源于stack exchange,提问作者Adam Stepniak
相关产品推荐
相关产品推荐

