Valgrind memcheck工具报告对于c ++没有匹配删除,但删除操作在另一个类/结构中

时间:2017-09-08 10:36:48

标签: c++ memory memory-leaks valgrind

我在data_buf.h中有一个结构:

struct DataBuffer {
  uint8_t* buffer;
  size_t buf_size;
  size_t data_start;
  size_t data_len;
  int dst_offset;

  DataBuffer(uint8_t* buf, size_t sz, size_t ds, size_t dl, int doff);
  ~DataBuffer();
};

data_buf.cpp

DataBuffer::DataBuffer(uint8_t* buf, size_t sz,
                   size_t ds, size_t dl,
                   int doff)
  :buffer{buf},
   buf_size{sz},
   data_start{ds},
   data_len{dl},
   dst_offset{doff} {}

DataBuffer::~DataBuffer() {
  if (buffer) {
  delete [] buffer;
  }
}

所以在类data_proc_hdl.h中:     #include“data_buf.h”

class DataProcessHandler {
 public:
  DataProcessHandler(int buf_len);

 private:
  DataBuffer m_data;
}

构造函数如下:

DataProcessHandler::DataProcessHandler(int buf_len)
  :m_data{new uint8_t[buf_len], buf_len, 0, 0, -1} {}

没有自定义类使用的析构函数。

ClientHandler派生自DataProcessHandler,

所以:

ClientHandler* u = new ClientHandler(10);
u->do_something();
delete u;

我认为没关系,分配的数据缓冲区将在DataBuffer中释放 析构函数,但Valgrind出局:

==12419== Mismatched free() / delete / delete []
==12419==    at 0x49421D4: operator delete[](void*) (vg_replace_malloc.c:621)
==12419==    by 0x10EABB: ~DataProcessHandler (data_proc_hdl.h:19)
==12419==    by 0x10EABB: ClientHandler::~ClientHandler()     (client_hdl.cpp:81)
==12419==    by 0x10EAE3: ClientHandler::~ClientHandler() (client_hdl.cpp:62)
==12419==    by 0x112EF3: ClientManager::process_client_disconn(ClientHandler*) (client_mgr.cpp:85)
==12419==    by 0x126153: Multiplexer::run() (multiplexer.cpp:182)
==12419==    by 0x11515F: main (cp_log.cpp:93)
==12419==  Address 0x4be50b0 is 0 bytes inside a block of size 256 alloc'd
==12419==    at 0x4940660: malloc (vg_replace_malloc.c:299)
==12419==    by 0x49FC5EB: operator new(unsigned long) (in /system/lib64/libc++.so)
==12419==    by 0x116E9B: DataProcessHandler::DataProcessHandler(int, LogController*, Multiplexer*, unsigned long) (data_proc_hdl.cpp:18)
==12419==    by 0x10E853: ClientHandler::ClientHandler(int, LogController*, Multiplexer*, ClientManager*) (client_hdl.cpp:50)
==12419==    by 0x112E07: ClientManager::process(int) (client_mgr.cpp:71)
==12419==    by 0x126153: Multiplexer::run() (multiplexer.cpp:182)
==12419==    by 0x11515F: main (cp_log.cpp:93)

Qestion:   是真的,有内存泄漏还是因为它不是像这样管理数据缓冲区的好设计?

1 个答案:

答案 0 :(得分:0)

不匹配的free()/ delete / delete []意味着您正在混淆分配和释放功能。

例如你可能

  • 使用malloc分配并取消分配deletedelete[]
  • 使用new分配并取消分配freedelete[]
  • 使用new[]分配并取消分配freedelete

(请注意,还有几个分配函数,如calloc和posix_memalign)

这可能导致泄漏,例如,如果您使用new进行分配并使用free解除分配,则析构函数将不会被调用,从而导致间接泄漏。

这也可能导致内存损坏和崩溃。例如,如果将malloc和new替换为使用不同内存池的版本。在这种情况下,如果您使用函数从错误的池中释放内存,则可能会损坏该池。

最后,这可能是虚假警报。特别是如果你有任何可以在优化代码中内联的替换函数,那么Valgrind将不会在callstack中看到内联函数。如果您在没有优化或“无内联”标志的情况下进行编译,则应该能够消除这种可能性。