这个问题是 my question 的延续.
这是有问题的代码。
嗯:
#include <string>
#include <vector>
std::vector<std::string> foo();
a.cpp
#include "a.h"
std::vector<std::string> foo()
{
std::vector<std::string> v;
return v;
}
最后是 main.cpp:
#include "a.h"
#include <iostream>
int main()
{
std::vector<std::string> s = foo();
return 0;
}
编译如下(main.cpp是带STL调试标志编译的):
g++ -c a.cpp
g++ -D_GLIBCXX_DEBUG main.cpp a.o
运行 a.out 时,进程崩溃:
Core was generated by `./a.out'.
Program terminated with signal 11, Segmentation fault.
#0 0x00007fe355998c43 in __gnu_debug::_Safe_iterator_base::_M_detach_single() () from /usr/lib64/libstdc++.so.6
(gdb) bt
#0 0x00007fe355998c43 in __gnu_debug::_Safe_iterator_base::_M_detach_single() () from /usr/lib64/libstdc++.so.6
#1 0x00007fe355999ebc in __gnu_debug::_Safe_sequence_base::_M_detach_all() () from /usr/lib64/libstdc++.so.6
#2 0x0000000000400cac in __gnu_debug::_Safe_sequence_base::~_Safe_sequence_base() ()
#3 0x0000000000400cc6 in __gnu_debug::_Safe_sequence<std::__debug::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >::~_Safe_sequence() ()
#4 0x0000000000400ce7 in std::__debug::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >::~vector() ()
#5 0x0000000000400c35 in main ()
我的海湾合作委员会:
Using built-in specs.
Target: x86_64-suse-linux
Configured with: ../configure --prefix=/usr --infodir=/usr/share/info --mandir=/usr/share/man --libdir=/usr/lib64 --libexecdir=/usr/lib64 --enable-languages=c,c++,objc,fortran,obj-c++,java,ada --enable-checking=release --with-gxx-include-dir=/usr/include/c++/4.4 --enable-ssp --disable-libssp --with-bugurl=http://bugs.opensuse.org/ --with-pkgversion='SUSE Linux' --disable-libgcj --disable-libmudflap --with-slibdir=/lib64 --with-system-zlib --enable-__cxa_atexit --enable-libstdcxx-allocator=new --disable-libstdcxx-pch --enable-version-specific-runtime-libs --program-suffix=-4.4 --enable-linux-futex --without-system-libunwind --with-arch-32=i586 --with-tune=generic --build=x86_64-suse-linux
Thread model: posix
gcc version 4.4.1 [gcc-4_4-branch revision 150839] (SUSE Linux)
最佳答案
您的问题是将 -D_GLIBCXX_DEBUG
仅传递给 a.cpp
。此标志将额外的调试信息添加到 STL 结构,因此它的用法必须在项目中的所有文件中保持一致。否则,不同的文件不同意 std::vector
和 std::string
的内存布局,导致未定义的行为(在您的情况下是崩溃)。
关于c++ - std::vector<std::string> 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4836344/