问题描述
如果我们想在C ++程序来检查内存泄漏,我们可以重载新
和删除
运营商可以跟踪被分配的内存。如果我们想做些什么检查在C程序中泄漏的?由于没有操作人员用C重载,我们可以在写的的malloc
函数指针拦截的malloc通话
和跟踪内存分配?有没有使用任何外部的实用程序更简单的方法?请提供一些code,因为我不熟悉过写作方法指针。
If we would like to check for memory leaks in a C++ program, we can overload the new
and delete
operators to keep track of the memory that was allocated. What if we would like to check for leaks in a C program? Since there is no operator overloading in C, can we over-write the malloc
function pointer to intercept calls to malloc
and track memory allocation? Is there an easier way without using any external utilities? Please provide some code as I am not familiar with over-writing method pointers.
请注意:我想练习做到这一点,无需任何外部应用
Note: I would like to do this without any external utilities for practice.
推荐答案
的建议,已经存在一些优秀的工具,像Valgrind的做到这一点。
As suggested, there already exist excellent tools like Valgrind to do this.
另外:
我想实践结果做到这一点,无需任何外部公用事业
这很有趣,我相信会是充实的,结果
您可以使用宏伎俩来检测这样的内存使用和泄漏错误,其实写自己的整齐检漏仪。您应该可以,只要你在你的项目中一个单独的分配和释放函数来做到这一点。
I would like to do this without any external utilities for practice
This is interesting and I am sure would be fulfilling,
You can use macro trick to detect such memory usage and leak errors, in fact write your own neat leak detector. You should be able to do this as long as you have a single allocation and deallocation function in your project.
#define malloc(X) my_malloc( X, __FILE__, __LINE__, __FUNCTION__)
void* my_malloc(size_t size, const char *file, int line, const char *func)
{
void *p = malloc(size);
printf ("Allocated = %s, %i, %s, %p[%li]\n", file, line, func, p, size);
/*Link List functionality goes in here*/
return p;
}
您保持地址的链接列表被分配与分配有所在的文件和行号。你在你的的malloc
更新条目的链接列表。
You maintain a Linked List of addresses being allocated with the file and line number from where there allocated. You update the link list with entries in your malloc
.
与上述类似,你可以写免费
的实施,其中您检查被要求的地址条目对你的链表被释放。如果没有匹配条目及其用法错误,您可以标记它如此。
Similar to above you can write an implementation for free
, wherein you check the address entries being asked to be freed against your linked list. If there is no matching entry its a usage error and you can flag it so.
在程序结束时,您打印或您的链接列表的内容写入到一个日志文件。如果没有泄漏你的链表应该没有条目,但如果有一些泄漏,那么日志文件给你,其中分配内存的确切位置。
At the end of your program you print or write the contents of your linked list to an logfile. If there are no leaks your linked list should have no entries but if there are some leaks then the logfile gives you exact location of where the memory was allocated.
请注意,在使用该宏招,你失去它的功能提供了类型检查,但它是一个整洁的小把戏我用了很多次了。
Note that in using this macro trick, you lose the type checking which functions offer but it's a neat little trick I use a lot of times.
希望这有助于一切顺利:)
Hope this helps and All the Best :)
这篇关于检测内存泄漏在C程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!