views:

54

answers:

2

Just curious, Is there or has anyone ever come across a heap / buffer overflow exception in C#?

A: 

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.

Aurojit Panda
+2  A: 

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.

Jim Mischel