c# – Bounds checking in managed and unmanaged code

Question:

1) How to force bounds checking in managed and unmanaged code?

2) How to catch such errors?

For example, for unmanaged code in the same Delphi there is an option Range Check Errors to catch such errors.

What can sharp offer us in this regard?

Answer:

Range Check Errors in Delphi are two separate features in C#/.NET

The first is a check for arithmetic overflow / underflow. Enabled in project properties, in Build / Advanced.

This check is valid only within checked regions. Those. it – will work by default – will not work inside unchecked { код } region – will work inside checked { код } region nested in unchecked

Pointers and fixed-size buffers can only be used inside unchecked regions, so in principle it can be said that checking only works for managed code.

Also, the arithmetic overflow / underflow option is an assembly attribute. Those. whether to enable validation for code within a particular DLL is determined at compile time. Setting this option causes the C# compiler to replace the IL commands for working with numbers – add , mul – with their counterparts that check for overflow – add.ovf , mul.ovf .

If the assembly is already ready and you just use it, then you will not be able to change the setting for the code inside it.


The second is the out-of-bounds check, and you can't turn it off for managed code.

In unmanaged code, on the contrary, it cannot be enabled. Simply because, in terms of unmanaged code, there are no arrays as such. There are pointers. There are functions for working with memory. And arrays as integral objects – a piece of memory + length – are not present.

In delphi, Range Check Errors only works with internal pascal arrays – which are actually quite manageable – the runtime knows about their length.

Scroll to Top