Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe vs Unsafe code

Tags:

c#

unsafe

Read this question today about safe and unsafe code I then read about it in MSDN but I still don't understand it. Why would you want to use pointers in C#? Is this purely for speed?

like image 793
Lumpy Avatar asked May 03 '10 20:05

Lumpy


People also ask

What is an unsafe code?

Unsafe code in general is a keyword that denotes a code section that is not handled by the Common Language Runtime(CLR). Pointers are not supported by default in C# but unsafe keyword allows the use of the pointer variables.

What is a safe and unsafe code in C#?

In this article, we are going to learn about the unsafe code in C#. In general, the code that we write in C# is safe code. It creates managed objects and doesn't access the memory directly. On the other hand, unsafe code in C# is code that is not in direct control of the Common Language Runtime (CLR).

Why is C++ considered unsafe?

C and C++ are unsafe in a strong sense: executing an erroneous operation causes the entire program to be meaningless, as opposed to just the erroneous operation having an unpredictable result. In these languages erroneous operations are said to have undefined behavior.

Is C++ an unsafe language?

You betcha (out-of-bounds write). These vulnerabilities and exploits, and many others, are made possible because C and C++ are not memory safe. Organizations which write large amounts of C and C++ inevitably produce large numbers of vulnerabilities that can be directly attributed to a lack of memory safety.


2 Answers

There are three reasons to use unsafe code:

  • APIs (as noted by John)
  • Getting actual memory address of data (e.g. access memory-mapped hardware)
  • Most efficient way to access and modify data (time-critical performance requirements)
like image 88
Keith Adler Avatar answered Oct 15 '22 13:10

Keith Adler


Sometimes you'll need pointers to interface your C# to the underlying operating system or other native code. You're strongly discouraged from doing so, as it is "unsafe" (natch).

There will be some very rare occasions where your performance is so CPU-bound that you need that minuscule extra bit of performance. My recommendation would be to write those CPU-intesive pieces in a separate module in assembler or C/C++, export an API, and have your .NET code call that API. An possible additional benefit is that you can put platform-specific code in the unmanaged module, and leave the .NET platform agnostic.

like image 24
John Källén Avatar answered Oct 15 '22 12:10

John Källén