这是一个相当大的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 );
}
当循环完成循环并返回向量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()是如何工作的。
答案 0 :(得分:2)
该堆栈跟踪的第9行让我相信所提到的向量正在进行双重删除。我会查看你放入该向量的类,并确保它们遵循三个规则,或者至少在删除它们之后将指针设置为null。
答案 1 :(得分:1)
在valgrind下运行您的程序,它可以帮助您诊断错误。