.NET 4:仅在托管代码可能导致堆损坏? [英] .NET 4: Can the managed code alone cause a heap corruption?

查看:196
本文介绍了.NET 4:仅在托管代码可能导致堆损坏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的多线程程序托管堆损坏。做一些测试,我发现,腐败只发生在后台线程程序中的活动状态(它们是切换)。该线程使用一些第三方组件。

I have a heap corruption in my multi-threaded managed program. Doing some tests I found that the corruption happens only when the background threads active in the program (they are switchable). The threads use some 3rd party components.

检查线程和第三方组件的代码(使用.NET反射)后,我发现他们都得到管理,即不安全或DllImportAttribute或P / Invoke的。看来,纯粹的托管代码会导致堆损坏,这可能吗?

After examining the code of the threads and 3rd party components (with .NET Reflector) I found that they are all managed, i.e. no "unsafe" or "DllImportAttribute" or "P/Invoke". It seems that the purely managed code causes a heap corruption, is this possible?

更新

除了使用Marshal类,是有可能损坏使用线程堆没有被正确同步?一个例子是非常赞赏。

Apart from using Marshal class, is it possible to corrupt the heap with threads not being correctly synchronized? An example would be very appreciated.

推荐答案

这是绝对有可能破坏堆没有任何使用不安全的代码。 Marshal类是你的朋友/敌人在这里

It's definitely possible to corrupt the heap without any use of unsafe code. The Marshal class is your friend / enemy here

IntPtr ptr = new IntPtr(50000);  // Random memory
byte[] b = new byte[100];
Marshalp.Copy(b, 0, ptr, 100);

这有效地拷贝100个连续的0到地址50000

This effectively copies 100 consecutive 0's into the heap at address 50000.

另一种方法是用明确的结构布局

Another way is with explicit struct layouts

[StructLayout(LayoutKind.Explicit)]
struct S1
{
    [FieldOffset(0)]
    internal string str;

    [FieldOffset(0)]
    internal object obj;
}

S1 s = new S1();
s.obj = new Program();
s.str.Trim();  // Hope that works ... :) 

这篇关于.NET 4:仅在托管代码可能导致堆损坏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆