这是一个相当大的C++程序的片段:
map<int, int>::iterator class_it = docsCountPerClass.begin();
for( ;class_it != docsCountPerClass.end(); class_it++) {
cout << "classid: " << class_it->first << '\n';
vector<term_importance> ti;
ti.reserve(termids.size());
vector<int>::iterator term_it = termids.begin();
for( ;(term_it != termids.end()); term_it++) {
term_importance tmp;
tmp.termid = *term_it;
tmp.importnaceMeasure = chiSquareTest(*term_it, class_it->first);
ti.push_back(tmp);
}
if(ti.size() != 0)
std::sort(ti.begin(), ti.end());
for(int i = 0; i < ti.size(); i++)
cout << (ti.at(i)).termid << " -- " << (ti.at(i)).importnaceMeasure << '\n';
int ti_size_tmp = ti.size();
for(int i = 0; i < std::min(maxFeaturesPerClass, int(ti.size()) ); i++) {
cout << "* index access: " << ti_size_tmp - 1 - i << '\n';
usefulTerms[class_it->first].push_back( (ti.at(ti_size_tmp - 1 - i)).termid );
}
当循环完成其循环并返回 vector ti时,我将面临的问题将被破坏。它可以,但是在清理其中的对象时会崩溃,并且报告它试图在无效指针上调用free()。我无法使用更简单的代码来重现该问题。这是使用gdb的回溯:
#0 0x0012d422 in __kernel_vsyscall ()
#1 0x00341651 in *__GI_raise (sig=6) at ../nptl/sysdeps/unix/sysv/linux/raise.c:64
#2 0x00344a82 in *__GI_abort () at abort.c:92
#3 0x0037849d in __libc_message (do_abort=2, fmt=0x44cf98 "*** glibc detected *** %s: %s: 0x%s ***\n") at ../sysdeps/unix/sysv/linux/libc_fatal.c:189
#4 0x00382591 in malloc_printerr (action=<value optimized out>, str=0x6 <Address 0x6 out of bounds>, ptr=0x81dc5e0) at malloc.c:6264
#5 0x00383de8 in _int_free (av=<value optimized out>, p=<value optimized out>) at malloc.c:4792
#6 0x00386ecd in *__GI___libc_free (mem=0x81dc5e0) at malloc.c:3738
#7 0x00297741 in operator delete(void*) () from /usr/lib/libstdc++.so.6
#8 0x08054377 in __gnu_cxx::new_allocator<NaiveBayesClassifier::term_importance>::deallocate (this=0xbffff194, __p=0x81dc5e0)
at /usr/include/c++/4.4/ext/new_allocator.h:95
#9 0x080522db in std::_Vector_base<NaiveBayesClassifier::term_importance, std::allocator<NaiveBayesClassifier::term_importance> >::_M_deallocate (this=0xbffff194,
__p=0x81dc5e0, __n=4433) at /usr/include/c++/4.4/bits/stl_vector.h:146
#10 0x0805219e in ~_Vector_base (this=0xbffff194, __in_chrg=<value optimized out>) at /usr/include/c++/4.4/bits/stl_vector.h:132
#11 0x08050139 in ~vector (this=0xbffff194, __in_chrg=<value optimized out>) at /usr/include/c++/4.4/bits/stl_vector.h:313
#12 0x0804d32d in NaiveBayesClassifier::buildModel (this=0xbffff28c, maxFeaturesPerClass=100) at NaiveBayesClassifier.cpp:106
#13 0x0805c357 in main (argc=2, argv=0xbffff3d4) at nbClassifyMain.cpp:15
编辑1:
NaiveBayesClassifier.cpp:http://paste.bradleygill.com/index.php?paste_id=49445
NaiveBayesClassifier.h:http://paste.bradleygill.com/index.php?paste_id=49446
编辑2:
我注释掉
std::sort(ti.begin(), ti.end());
,发现错误消失了。现在我很困惑std::sort()的工作方式。 最佳答案
该堆栈跟踪的第9行使我相信所提到的 vector 正在执行两次删除。我将研究放入该 vector 中的类,并确保它们遵循三个规则,或者至少在删除它们后将指针设置为null。
关于c++ - 对象的破坏导致程序崩溃,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3720640/