c++ - 使用 libproc 时如何正确释放内存

标签 c++ c

我按照 http://ewencumming.blogspot.cz/2012/02/list-processes-using-libproc.html 上的示例进行操作为了浏览Linux内核上正在运行的进程。然而我发现代码有泄漏:

#include <stdio.h>
#include <string.h>
#include <proc/readproc.h>

int main(int argc, char** argv)
{
 // fillarg used for cmdline
 // fillstat used for cmd
 PROCTAB* proc = openproc(PROC_FILLARG | PROC_FILLSTAT);

 proc_t proc_info;

 // zero out the allocated proc_info memory
 memset(&proc_info, 0, sizeof(proc_info));

 while (readproc(proc, &proc_info) != NULL) { // <<!!!!!! here is the leak !!!!!!
  // do something
 }

 closeproc(proc);
}

在循环中运行此代码(整个主代码)会分配内存,但不会释放它。

根据 libproc 源代码中的注释,应该在某个地方调用 freeproc(),但是在任何地方调用它只会使应用程序崩溃(应该在 readproc 缓冲区返回 NULL 时调用它)。

如何正确释放readproc分配的内存? (该库是用 c 编写的,但我正在编写的代码是用 c++ 编写的,所以我对两者都进行了标记)

最佳答案

来自the manpage :

readproc reads the information for the next process matching the criteria specified in PT and fills them into a proc_t structure. If return_buf is not NULL, it will use the struct pointed at by return_buf. Otherwise it will allocate a new proc_t structure and return a pointer to it. Note that (if so specified in PT) readproc always allocates memory if it fills in the environ or cmdline parts of proc_t.

freeproc frees all memory allocated for the proc_t struct *p.

您正在使用PROC_FILLARG,它“填充proc_tcmdline部分,因此最终的粗体句子被激活。这意味着struct 由 readproc 分配,但您忽略了可以在其中找到指向该结构的指针的返回值;该结构与您正在使用的结构不同,并且稍后尝试释放 -永远不要释放具有自动存储持续时间的对象(“在堆栈上”)!这就是您崩溃的原因。

您应该将 return_buf 的返回值分配给一个指针,并使用它:

int main(int argc, char** argv)
{
 // fillarg  used for cmdline
 // fillstat used for cmd
 PROCTAB* proc = openproc(PROC_FILLARG | PROC_FILLSTAT);

 while (proc_t* proc_info = readproc(proc, NULL)) {
    // do something
    freeproc(proc_info)
 }

 closeproc(proc);
}

关于c++ - 使用 libproc 时如何正确释放内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17359517/

相关文章:

c++ - cppitertools:如何结合 iter::enumerate 和 iter::filter?

c++ - 带有 QPushButton、QComboBox QCheckbox 的动态小部件列表

c++ - 使用 const double* const 作为模板参数 - 代码性能问题

c - 向链表添加项目并分配空间

c++ - 从内存中绘制位图

c++ - OpenCV HoughCircles

C++程序根据特定规则接受一个字符串(num opr num)

c++ - 从 Julia 调用 C/C++

c - 输出中的双数组字符串互连 - C 编程

c - 如何降低 Intel C\C++ 编译器中的错误检查级别