c# - 在 C# 中检查堆完整性和堆栈大小

标签 c# heap-memory stack-memory

我正在尝试追踪当我对 C# 代码施加压力并在低内存条件下运行时发生的崩溃。但是,在某些情况下,我的程序不会出现 OutOfMemoryException,而是会崩溃并退出。这通常是由缓冲区溢出或堆栈溢出(或损坏)引起的内存损坏引起的。

那么,有没有办法检查堆的完整性,或者有没有办法检查线程上还剩下多少堆栈?

出于速度原因,我使用了很多不安全的代码,所以很可能我的代码在某处破坏了内存。不幸的是,崩溃发生在损坏发生后的随机时间间隔内。我知道 C# 会在检测到缓冲区溢出时关闭应用程序,但有没有办法强制它进行检查?

谢谢。

最佳答案

您可以使用 Constrained Execution Regions 处理这些情况:

A constrained execution region (CER) is part of a mechanism for authoring reliable managed code. A CER defines an area in which the common language runtime (CLR) is constrained from throwing out-of-band exceptions that would prevent the code in the area from executing in its entirety. Within that region, user code is constrained from executing code that would result in the throwing of out-of-band exceptions. The PrepareConstrainedRegions method must immediately precede a try block and marks catch, finally, and fault blocks as constrained execution regions. Once marked as a constrained region, code must only call other code with strong reliability contracts, and code should not allocate or make virtual calls to unprepared or unreliable methods unless the code is prepared to handle failures. The CLR delays thread aborts for code that is executing in a CER.

当然,CER 的限制非常多。你不能在他们身上做太多。它们专为关键的小部分代码而设计。

关于c# - 在 C# 中检查堆完整性和堆栈大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1638000/

相关文章:

c# - websocket 成功握手,但没有正确发送接收消息(C# 服务器)

c++ - 错误 : AddressSanitizer: heap-buffer-overflow on address X at pc Y bp Z sp W

pointers - 获取当前进程堆的起始地址?

java - java内存分配

c# - 处理由另一个应用程序创建的 .dat 文件

c# - c# 一条语句中的多个内联赋值

c# - 是扩展绑定(bind)

tomcat - Windows 更新后 JVM 内存初始化错误

无法在 C 中释放重新分配的内存

assembly - 在 x86 程序集的过程中调用 ret 指令的位置是否重要