下面給出導致出現分段錯誤的部分代碼。關閉二進制文件時出現分段錯誤
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進行編譯。
蘇雷什
嘗試'拷貝(xi_in,ii_t(),xi.data());'。還要確保收件人已經足夠大了。 –
您能否提供一個可以演示問題的最小可編譯示例。 –
@KerrekSB是的,它只是ii_t - 它是錯字。謝謝 – suresh