C++ std::vector 的指针删除和分段错误 [英] C++ std::vector of pointers deletion and segmentation faults

查看:68
本文介绍了C++ std::vector 的指针删除和分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个指向类的指针向量.我需要调用它们的析构函数并释放它们的内存.由于它们是指针向量 vector.clear() 不能完成这项工作.所以我继续像这样手动进行:

I have a vector of pointers to a class. I need to call their destructors and free their memory. Since they are vector of pointers vector.clear() does not do the job.So I went on to do it manually like so :

void Population::clearPool(std::vector<Chromosome*> a,int size)
{
    Chromosome* c;
    for(int j = 0 ;j < size-1;j++)
    {
       c = a.back();
       a.pop_back();
       delete c;
       printf("  %d 

",j);
       c = NULL;

    }

}

其中的 printf 是因为我有一个会说话的析构函数来查看分段错误发生在哪个染色体中.当调用 clearPool() 并说我们的大小为 100 时,它会在 0 到 100 之间的任何染色体中给出分段错误.

The printf in there is since I have a talking destructor to see in which Chromosome the segmentation fault happens. When clearPool() is called and say we got a size of 100, it can give a segmentation fault in any Chromosome between 0 and 100.

我不知道为什么会发生这种情况,也没有办法真正找到问题所在,因为在使用断点进行调试时,我看到的只是它发生在随机染色体上.

I have no idea why this might be happening nor do I have a way to actually find what's wrong since while debugging with breakpoints all I see is that it happens in there at random chromosomes.

我正在使用 codeblocks IDE 和 gdb 调试器.发生分段错误时的堆栈跟踪有 4 个内存地址和一个函数 wsncpy().

I am using codeblocks IDE and the gdb debugger. The stack trace when the segmentation fault happens has 4 memory addresses and a function wsncpy().

推荐答案

void Population::clearPool( std::vector <Chromosome*> & a )
{
   for ( int i = 0; i < a.size(); i++ ) {
      delete a[i];
   }
   a.clear();
}

请注意,向量是通过引用传递的.在您的代码中,使用了向量的副本,这意味着它在调用程序中没有改变.因为您删除了副本中的指针,所以原始指针现在全部无效 - 我怀疑您正在以某种方式使用这些无效指针,而这些指针未在您发布的代码中显示.

Notice that the vector is passed by reference. In your code, a copy of the vector is used, which means that it is unchanged in the calling program. Because you delete the pointers in the copy, the pointers in the original are now all invalid - I suspect you are using those invalid pointers in some way not shown in the code you posted.

由于已经发布了几个使用 C++ 库算法的模板解决方案,您可能还想考虑一个不使用的模板解决方案:

As a couple of template solutions have been posted that use C++ library algorithms, you might also want to consider a template solution that does not:

template <class C> void FreeClear( C & cntr ) {
    for ( typename C::iterator it = cntr.begin(); 
              it != cntr.end(); ++it ) {
        delete * it;
    }
    cntr.clear();
}

使用这个你可以释放任何动态分配对象的容器:

Using this you can free any container of dynamically allocated objects:

vector <Chromosome *> vc;
list <Chromosome *> lc;
// populate & use
FreeClear( lc );
FreeClear( vc );

这篇关于C++ std::vector 的指针删除和分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆