如何计算使用Malloc和New动态分配内存的所有指针和变量?
如果我们覆盖Malloc和新功能,我们可以跟踪首先创建的指针。但是,如何跟踪和计算使用此分配的内存的其他指针和功能? (Q Pointer在下面的代码下)我应该覆盖分配运算符和函数调用吗?如果是的话?如果解决方案是将参考计数与类,构造函数和驱动器一起使用,我必须将所有正常的指针定义更改为类类型?我不想更改源代码只想包括一个库,并将指针计入分配的内存。
int ∗ p = (int∗)malloc(10 ∗ sizeof (int));
int * q= p;
if we override malloc and new function we can track first created pointer . but how can i track and count other pointers and functions that using this allocated memory ? (q pointer in below code ) should i override Assignment operator and function call ? if yes how ? if the solution is to use reference counting with class and constructor and destructor i have to change all normal pointer definitions to class type ? i dont want change source code just want to include a library and count pointers to an allocated memory.
int ∗ p = (int∗)malloc(10 ∗ sizeof (int));
int * q= p;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
C ++根本无法以这种方式工作。指针是指针,一个内存地址。没有其他与之相关的行李,可以用来以某种形式或方式将其保留。指向班级的指针可以转换为指向其子类之一的指针,反之亦然。您现在得到一个完全不同的指针。原始指针可能不再存在,而其他相关指针仍然可以保留。
到达数组的指针可能会执行一些数学,从而导致了另一个指针,然后在更多数学后,原始指针又回来了。
一个怪异的C ++程序可以将原始指针编写为文件,然后摆脱该指针,它不再存在,然后一段时间后将其回复,然后您有,相同的指针又回来了,并且使用它仍然是,非常有效,仍然有效。
一旦覆盖
malloc
将不再被控制在刚刚迈出的指针上,并且在发生的事情上没有进一步的说法,直到免费
得到它。希望它会是相同的指针,一切都会好起来的。这就是C ++的指针的工作方式。它们是无法控制的,难以控制。诸如Java,C#或Perl之类的更高级别的编程语言,跟踪其所有指针并管理它们,必须将其内置在编程语言本身的核心中,对于C ++而言,情况并非如此。 C ++不是Java,C#或任何其他语言。在C ++中,该计划有责任跟踪它们并正确使用它们。 C ++不会为您做到这一点。
C++ simply does not work this way, on a fundamental level. A pointer is a pointer, a memory address. There is no other baggage associated with it, that can be used to keep tabs on it in some form or fashion. A pointer to a class can be converted to a pointer to one of its sub-classes, and vice versa. You now get a completely different pointer. The original pointer may no longer exist, but other, related pointers can still remain.
A pointer to an array may have some math performed on it, resulting in a different pointer, then after more math the original pointer comes back.
A weird C++ program may write the raw pointer to a file, then get rid of this pointer, it no longer exists, then some time later read it back, and there you have it, the same pointer is back, and using it is still, very much, well-formed, and it still works.
Once an overridden
malloc
hands over a freshly-minted pointer it is no longer under its control, and has no further say in what happens to it, untilfree
gets it. Hopefully it'll be the same pointer, and everything will be ok.That's how C++'s pointers work. They are uncontrollable, and unmanageable. Higher-level programming languages like Java, C#, or Perl, keep track of all their pointers and manage them, this must be built into the core of the programming language itself, which is not the case for C++. C++ is not Java, C#, or any other language. In C++ it is the program's responsibility to keep track of them, and use them properly. C++ will not do that for you.