Heap / buffer overflow exception

久未见 提交于 2019-12-05 15:23:24

You can cause a buffer overflow in C# in unsafe code. For example:

public unsafe struct testo
{
    public int before;
    public fixed int items[16];
    public int after;
}

testo x = new testo();
x.after = 1;
for (int i = 0; i <= 16; ++i)
{
    unsafe
    {
        x.items[i] = 99;
     }
}
Console.WriteLine(x.after);

The above will print "99" because it overflowed the buffer.

Absent unsafe code, I do not know of any way to cause a buffer overrun that doesn't trigger an exception.

Depending on what you mean by Buffer overflow, an IndexOutOfRangeException is an exception caused by overflow. You can get it rather easily by accessing an array index beyond its allocation size. Similarly do enough recursion and you can get StackOverflowException. I am not sure about what you're looking for, so you might want to clarify.

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