.NET 4: Can the managed code alone cause a heap corruption?

半世苍凉 提交于 2019-12-21 07:25:19

问题


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.

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?

UPDATE

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


回答1:


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);

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 ... :) 


来源:https://stackoverflow.com/questions/7574153/net-4-can-the-managed-code-alone-cause-a-heap-corruption

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!