gpt4 book ai didi

C++如何检查对堆内存的访问

转载 作者:行者123 更新时间:2023-11-28 02:26:40 24 4
gpt4 key购买 nike

我有以下问题。我不是如果可能以及如何。我想了解代码何时使用在堆中分配的内存地址(对于所有类型的内置对象和用户定义的对象)。例如:

char* p= new char[60];
strcpy(p,"home"); // statement A

有一种方法可以理解“语句 A”正在使用堆中分配的地址“p”吗?通过重新定义 operator new,我可以存储堆地址,但是如何理解某些指令何时使用它们?我想以对用户透明的方式执行此操作。

非常感谢

****** 一个例子

char* p= new char[60];
delete [] p;
strcpy(p,"home"); // statement A

我想警告这个无效的内存访问。为此,我必须了解 strcpy 正在尝试访问地址 p,以便我可以对 p 的有效性执行一些测试。

最佳答案

看这个:http://www.hboehm.info/gc/gcdescr.html它是 C/C++ 的透明垃圾收集器。它以您描述的方式跟踪存在哪些引用内存位置的指针:

At each collection, the collector marks all objects that are possibly reachable from pointer variables. Since it cannot generally tell where pointer variables are located, it scans the following root segments for pointers:

The registers. Depending on the architecture, this may be done using assembly code, or by calling a setjmp-like function which saves register contents on the stack. The stack(s). In the case of a single-threaded application, on most platforms this is done by scanning the memory between (an approximation of) the current stack pointer and GC_stackbottom. (For Itanium, the register stack scanned separately.) The GC_stackbottom variable is set in a highly platform-specific way depending on the appropriate configuration information in gcconfig.h. Note that the currently active stack needs to be scanned carefully, since callee-save registers of client code may appear inside collector stack frames, which may change during the mark process. This is addressed by scanning some sections of the stack "eagerly", effectively capturing a snapshot at one point in time.

Static data region(s). In the simplest case, this is the region between DATASTART and DATAEND, as defined in gcconfig.h. However, in most cases, this will also involve static data regions associated with dynamic libraries. These are identified by the mostly platform-specific code in dyn_load.c.

The marker maintains an explicit stack of memory regions that are known to be accessible, but that have not yet been searched for contained pointers. Each stack entry contains the starting address of the block to be scanned, as well as a descriptor of the block. If no layout information is available for the block, then the descriptor is simply a length. (For other possibilities, see gc_mark.h.)

正如您所想象的,您必须真正卷起袖子并做一些非常低级的 hack 来管理它,像这样扫描内存是一件昂贵的事情,所以我认为您不能为了安全而这样做反对悬挂指针的原因。

我建议不要尝试如此透明地执行此操作。让用户获得像智能指针这样的对象的句柄,这样就可以更容易地实现垃圾收集或针对悬空指针或任何您喜欢的安全措施。 C++ 擅长那些类型的半透明解决方案,您可以在其中创建感觉像指针的对象并提供相同的运算符,但可以在上面做任何您想做的事情。

关于C++如何检查对堆内存的访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30410554/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com