如何查找使用动态分配的内存的对象和功能?
如果我们有这样的代码:
void g(int *n){
int m=n[1];
n= null ;
}
void main(){
int ∗ p = (int∗)malloc(10 ∗ sizeof (int));
int * q= p;
g(p);
}
因此,我们知道我们是否超载malloc,calloc,realloc,新,免费和删除功能,我们可以跟踪使用此功能创建或删除的第一个指针(上面的示例中的P Pointer),但是我如何找到并跟踪使用此分配的内存的其他指针和功能? (在上面的示例中,Q指针和G函数)。我应该超载分配语句和功能调用吗?如果是的话?换句话说,我也想知道现场对象以及分配的内存的最后使用时间和位置。 我想实现自定义内存泄漏检测工具,因此我需要在报告是否泄漏之前使用分配的内存来查找所有对象和指针。
if we have a code like this :
void g(int *n){
int m=n[1];
n= null ;
}
void main(){
int ∗ p = (int∗)malloc(10 ∗ sizeof (int));
int * q= p;
g(p);
}
so we know if we overload malloc, calloc , realloc ,new ,free and delete functions we can track first pointer that create or delete with this functions(p pointer in above example ) but how can i find and track other pointers and functions that using this allocated memory ? ( q pointer and g function in above example ) .should i overload Assignment statement and function call ? if yes how ? in other words i want to know live objects and last used time and location of an allocated memory too .
i want to implement an custom memory leak detection tools so i need to find all objects and pointer that using an allocated memory before report it that's leak or not .
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您所说的称为参考计数。搜索 stackoverflow 以下主题为您提供了这些结果:
? CPP/MONEME/shared_ptr“ rel =” nofollow noreferrer“> std :: shared_ptr 这样做。
我们需要跟踪资源的生命周期,通过控制创建,复制和删除是可能的。如果您在不使用类的情况下这样做,您将最终获得一些函数,一个状态变量和全局变量。这对于将共享资源的概念保持在用户的脑海中不是很有效。人们倾向于忘记,一个人正在使用共享资源,因为人们看到裸指针,并且倾向于像一个指针一样使用它,这会无视所提供的共享点数功能。
如果要将功能封装在类中,则应该需要为所有类型的概念实现,即您应该使用模板。一种方法就是这样:
我只对此代码进行了测试,因此我将其留给您进行测试和改进。
What you're talking about is called reference counting. Searching stackoverflow for this topic gives you these results:
The standard template library already has a std::shared_ptr which does that.
We need to keep track of the lifecycle of the resource, this is possible by controlling the creation, the copying and the deletion. If you do it without using a class, you'll end up with some functions, a state variable and a global variable. This is not very effective in keeping the concept of the shared resource in the focus of the user's mind. One tends to forget that one is using a shared resource because one sees a naked pointer and tends to use it like one, which would disregard the provided shared-pointer functionality.
If you were to encapsulate the functionality in a class, you should want to implement the concept for all types i.e. you should want to use templates. one way would be this:
I've tested this code only rudimentarily so I'll leave it to you to test and improve it.