c++ - 我应该如何关注 valgrind 中阻止的损失

标签 c++ memory-leaks valgrind

在我的代码中我有一个类 lipid其中包含三个 bead小号:

struct lipid{
  particle mainPart;
  bead * head;
  bead * body;
  bead * tail;
  int LID;
  vec direction;
  bead * operator[](int index){
    switch(index){
    case 0: return head;
    case 1: return body;
    case 2: return tail;
    default: return body;
    }
  }
};


struct bead{
  particle mainPart;
  int charge;
  int type;
  double rho;
  double nextRho;
  int LID;
  double U;
  double nextU;
  bool touch;
};


struct particle{
  vec pos;
  vec oldPos;
  vec vel;
  vec oldVel;
  vec F;
  vec oldF;
 };

class vec{
  velarry<double> coor;
  double x;
  double y;
  double z;
}

当我尝试创建脂质时,我使用新的创建了三个珠子

lipid * l = new lipid;
l->head = new bead;
l->body = new bead;
l->tail = new bead;

当我对我的代码进行 valgrind 时,我收到一个错误,声称有大量 block 丢失...我应该对此有多担心?我应该声明我正在插入 bead s 和 lipid s 变成(几个) vector 。

编辑 好的,添加 delete head .. 解决了这个问题,但我仍然有一个痛苦的问题,我有一行:

this->beadBoxes[t[0]][t[1]][t[2]].push_back(b);

在哪里tvector<int>尺寸 3 和 beadsBoxes是:

<vector<vector<vector<vector<bead*> > > > beadBoxes;

这家伙给了我 5 次内存泄漏错误:

==22458== 48 bytes in 2 blocks are definitely lost in loss record 11 of 106
==22458==    at 0x4A0666E: operator new(unsigned long) (vg_replace_malloc.c:220)
==22458==    by 0x419A3C: __gnu_cxx::new_allocator<bead*>::allocate(unsigned long, void const*) (new_allocator.h:88)
==22458==    by 0x419A64: std::_Vector_base<bead*, std::allocator<bead*> >::_M_allocate(unsigned long) (stl_vector.h:127)
==22458==    by 0x423E1F: std::vector<bead*, std::allocator<bead*> >::_M_insert_aux(__gnu_cxx::__normal_iterator<bead**, std:\
:vector<bead*, std::allocator<bead*> > >, bead* const&) (vector.tcc:275)
==22458==    by 0x424073: std::vector<bead*, std::allocator<bead*> >::push_back(bead* const&) (stl_vector.h:610)
==22458==    by 0x409664: membrane::updateBox(bead*) (membrane.cpp:874)
==22458==    by 0x40ACA5: membrane::decide(lipid*) (membrane.cpp:793)
==22458==    by 0x40DF01: membrane::rotate() (membrane.cpp:529)
==22458==    by 0x40DFAF: membrane::MCstep() (membrane.cpp:480)
==22458==    by 0x401B54: main (main.cpp:15)

我怀疑这可能与发生在该行上的段错误有关。为什么会出现新的(unsigned long)以及它为什么会抛出段错误?

最佳答案

您是否释放了使用 new 分配的对象?

为了一致的行为,您应该考虑使用构造函数和析构函数:

struct lipid{
    // constructor
    lipid() {
        this->head = new bead;
        this->body = new bead;
        this->tail = new bead;
    }
    // destructor
    ~lipid() {
        delete this->head;
        delete this->body;
        delete this->tail;
    }
    ... // rest of the class

关于c++ - 我应该如何关注 valgrind 中阻止的损失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6909759/

相关文章:

c++ - 错误 'a.out' : free(): invalid next size (normal)

delphi - 释放的 TStringList 在 FastMM4 报告中算作内存泄漏的原因

c - 函数没有及时释放

c - 8 Valgrind 的无效写入大小

c++ - C++实现合并排序的运行时错误

c++ - 是否可以检查共享指针是否在 native 单元测试中返回 nullptr?

c# - SharePoint 代码中的内存泄漏?

c - 分配还是不分配。大小 1 错误的读取无效。 【凝视2小时】

c - 为什么我的变量没有初始化?

c++ - 您将如何构建物理引擎中的类交互?