当仍有可到达的分配时,如何使 valgrind 报告错误
我正在编写一个生成 C 代码的编译器。生成的程序仅包含 main 函数,并且它们使用大量内存,这些内存是通过 malloc() 分配的。分配的大部分内存仅在程序的一小部分中使用,我认为在使用后释放它是一个好主意,因为它不会再次使用。那么,如果 valgrind 在程序结束时向我报告内存未 free()d,即仍然可达的内存,我会很高兴。我在 Makefile 中使用 valgrind 和 --error-exitcode=1 来自动检查此类问题。
问题是:有没有办法让 valgrind 以 1 退出,以防仍有可到达的分配?
I'm writing a compiler that produces C code. The programs produced consist only of the main function, and they use a lot of memory, that is allocated with malloc(). Most of the memory allocated is used only in a small part of the program, and I thought it would be a good idea to free() it after use, since it's not going to be used again. I would be glad, then, if valgrind would report to me about memory not free()d in the end of the program, that is, still reachable memory. I'm using valgrind with --error-exitcode=1 inside a Makefile, to check for this kind of problem automatically.
The question is: is there a way to make valgrind exit with 1 in case there are still reachable allocs?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
通过 Valgrind 输出进行 grep 的另一种方法:修改编译器,使其发出:
假设您没有将分配的块分配给全局变量(这没有意义,因为您只有一个函数),您刚刚将“仍然可达”转换为“肯定泄露了”。
可能更好的转换:不要在 main 中调用
exit(0)
;将其更改为return 0;
。最终效果应该与上面相同 -__libc_main
现在将为您调用exit
,并且main
中的所有局部变量都将超出范围到那时。An alternative to grepping through Valgrind output: modify your compiler so it emits:
Assuming you are not assigning allocated blocks to global variables (which would make no sense since you only have one function), you've just transformed "still reachable" into "definitely leaked".
Possibly even better transformation: don't call
exit(0)
in your main; change it toreturn 0;
instead. The net effect should be same as above --__libc_main
will now callexit
for you, and all local variables inmain
will be out of scope by that time.valgrind 手册 说:
我发现没有办法让 valgrind 报告“仍然可达”错误。似乎执行此操作的唯一选择(除了修补 valgrind 之外)是捕获 valgrind 的输出并解析“仍然可达”行。
The valgrind manual says:
I have found no way to make valgrind report "still reachable"s as error. It seems to be that your only option to do this (other than patching valgrind) is to capture the output of valgrind and parse the "still reachable" line.
当退出时存在可到达块时,用于错误退出的 poroper 选项:
valgrind --tool=memcheck --leak-check=full --show-reachable=yes --errors-for-leak-kinds =all
来自 Valgrind 手册:
The poroper options to use to exit with error when there is a reachable block at exit:
valgrind --tool=memcheck --leak-check=full --show-reachable=yes --errors-for-leak-kinds=all
From Valgrind manual:
或者,您可以在 makefile 中包含一个小 shell 脚本,用于 grep valgrind 的输出日志并相应退出。
Alternatively you can have a small shell script in your makefile to grep through output logs of valgrind and exit accordingly.