引起分段错误的代码部分如下所示。
ifstream xiFileId(xifile, ios::binary); //xifile is a char *
//the ii_t class in the following line is taken from http://stackoverflow.com/questions/1855704/c-binary-file-i-o-to-from-containers-other-than-char-using-stl-algorithms written by http://stackoverflow.com/users/14065/loki-astari
ii_t<uint> xi_in(xiFileId);
copy(xi_in, ii_t<uint>(), xi.data()); //xi is a 2D boost::multi_array
//my efforts to debug
ios::iostate s = xiFileId.rdstate();
if(s & ios::badbit) cout << "bad bit is set" << endl;
if (s & ios::failbit) cout << "fail bit is set" << endl;
if (s & ios::eofbit) cout << "eof bit is set" << endl;
if (s & ios::goodbit) cout << "good bit is set" << endl;
xiFileId.close(); //this line creates the seg violation
发现failbit
和eof
位已设置。使用valgrind
发现我的整个程序没有内存泄漏。
对于另一个二进制文件重复相同的代码(如上所述),并且在关闭该文件时(该文件先前关闭)不会出现分段错误,即使该文件同时设置了失败和eof位。
使用gdb和核心文件识别文件关闭引起的分段错误,如下所示。
#0 0x00007f16ad99ae50 in __libc_free (mem=0x1b8f930) at malloc.c:3724
3724 malloc.c: No such file or directory.
in malloc.c
(gdb) bt
#0 0x00007f16ad99ae50 in __libc_free (mem=0x1b8f930) at malloc.c:3724
#1 0x00007f16ae1adf0e in std::basic_filebuf<char, std::char_traits<char> >::_M_destroy_internal_buffer() () from /usr/lib/libstdc++.so.6
#2 0x00007f16ae1af4d4 in std::basic_filebuf<char, std::char_traits<char> >::close() () from /usr/lib/libstdc++.so.6
#3 0x00007f16ae1b133d in std::basic_ifstream<char, std::char_traits<char> >::close() () from /usr/lib/libstdc++.so.6
#4 0x000000000040c119 in main (argc=19, argv=0x7fff05849898) at prediction.cpp:161
如果我删除xiFileId.close();
,因为编译器会在文件超出范围时关闭文件,gdb后跟踪会给出以下内容:
#0 0x00007f97fab81e50 in __libc_free (mem=0x15a7930) at malloc.c:3724
3724 malloc.c: No such file or directory.
in malloc.c
(gdb) bt
#0 0x00007f97fab81e50 in __libc_free (mem=0x15a7930) at malloc.c:3724
#1 0x00007f97fb394f0e in std::basic_filebuf<char, std::char_traits<char> >::_M_destroy_internal_buffer() () from /usr/lib/libstdc++.so.6
#2 0x00007f97fb3964d4 in std::basic_filebuf<char, std::char_traits<char> >::close() () from /usr/lib/libstdc++.so.6
#3 0x00007f97fb39c966 in std::basic_ifstream<char, std::char_traits<char> >::~basic_ifstream() () from /usr/lib/libstdc++.so.6
#4 0x000000000040c184 in main (argc=19, argv=0x7fff59b71918) at prediction.cpp:163
表示调用~basic_ifstream()
并发生分段违规。
文件关闭在什么条件下可以创建seg违规?
有关如何进一步调查/修复它的任何想法?
此代码在Ubuntu 10.04上运行,并使用gcc版本4.4.3进行编译。
苏雷什
答案 0 :(得分:1)
评论中已经提到了解决方案,但是为了方便未来的读者,它会单独作为答案发布。
问题在于ii_t
类,并在Segmentation fault on boost::multi_array中提供了解决方案
https://stackoverflow.com/users/12711/michael-burr