提问人:Elhazin 提问时间:7/17/2023 最后编辑:Elhazin 更新时间:7/17/2023 访问量:98
leaks 命令未检测到 C 程序中的内存泄漏
leaks command not detecting memory leaks in C program
问:
我有一个 C 程序,我怀疑内存泄漏的存在
#include <stdio.h>
#include <stdlib.h>
char *f()
{
return (char *)malloc(10);
}
int main()
{
f();
system("leaks a.out");
return 0;
}
f()
函数使用 malloc
分配 10 字节的内存,但我没有在程序终止之前释放它。尽管在终端中使用了“leaks”命令,但它不会报告任何内存泄漏。
我还尝试在睡眠
时添加延迟,希望它能让“泄漏”命令有足够的时间来检测泄漏,但没有检测到泄漏。
为什么在这种情况下,“leaks”命令无法检测到内存泄漏?是否有其他方法或工具可以有效地识别 C 程序中的内存泄漏?
谢谢你的帮助。
答:
0赞
Ted Lyngmo
7/17/2023
#1
编译器可以优化对 的调用(以及对 的调用),因为您从不使用 from 的返回值,并且 in 中的任何内容都不会产生任何其他明显的副作用。例如,GCC 将程序编译为:f()
malloc
f
f
f:
mov edi, 10
jmp malloc
.LC0:
.string "leaks a.out"
main:
sub rsp, 8
mov edi, OFFSET FLAT:.LC0
call system
xor eax, eax
add rsp, 8
ret
...正如你所看到的,没有来自 的调用。f
main
如果你做 ,编译器也可以确保它根本不需要保留在那里并完全删除它:f
static
f
.LC0:
.string "leaks a.out"
main:
sub rsp, 8
mov edi, OFFSET FLAT:.LC0
call system
xor eax, eax
add rsp, 8
ret
评论
f()
system
leaks ./a.out
f
-O2
f