我按照 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 aproc_t
structure. Ifreturn_buf
is notNULL
, it will use the struct pointed at byreturn_buf
. Otherwise it will allocate a newproc_t
structure and return a pointer to it. Note that (if so specified inPT
)readproc
always allocates memory if it fills in theenviron
orcmdline
parts ofproc_t
.
freeproc
frees all memory allocated for theproc_t
struct*p
.
您正在使用PROC_FILLARG
,它“填充proc_t
的cmdline
部分,因此最终的粗体句子被激活。这意味着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/