All about Unsafe code in C #
C #. net hides most of memory management, which makes it much easier for the developer. thanks for the garbage collector and the use of references. but to make the language powerful enough in some cases in which we need direct access to the memory, Unsafe code was too Ted.
Commonly while programming in the. NET Framework we don? T need to use unsafe code, but in some cases there is no way not to, such as the following:
- Real-time applications, we might need to use pointers to enhance performance in such applications.
- External functions, in non-.net DLLs some functions requires a pointer as a parameter, such as Windows APIs that were written in C.
- Debugging, sometimes we need to inspect the memory contents for debugging purposes, or you might need to write an application that analyzes another application process and memory.
Unsafe code is mostly about pointers which have the following advantages and disadvantages.
Advantages of Unsafe code in C #:
- Performance and flexibility, by using pointer you can access data and manipulate it in the most efficient way possible.
- Compatibility, in most cases we still need to use old windows APIs, which use pointers extensively. or third parties may supply DLLs that some of its functions need pointer parameters. although this can be done by writing the dllimport declaration in a way that avoids pointers, but in some cases it? S just much simpler to use pointer.
- Memory addresses, there is no way to know the memory address of some data without using pointers.
Disadvantages
Of Unsafe code in C #:
- Complex syntax, to use pointers you need to go throw more complex syntax than we used to experience in C #.
- Harder to use, you need be more careful and logical while using pointers, Miss using pointers might lead to the following:
- Overwrite other variables.
- Stack Overflow.
- Access areas of memory that doesn? T contain any data as they do.
- Overwrite some information of the code for the. NET runtime, which will surely lead your application to crash.
- Your code will be harder to debug. A simple mistake in using pointers might lead your application to crash randomly and unpredictably.
- Type-safety, using pointers will cause the code to fail in the. NET type-safety checks, and of course if your security police don? T allow non type-safety code, then the. NET Framework will refuse to execute your application.
After we knew all the risks that might face us while using pointer and all the advantages those pointers introduces us of performance and flexibility, let us find now how to use them. the keyword unsafe is used while dealing with pointer, the name reflects the risks that you might face while using it. let? S See where to place it. We can declare a whole class as unsafe:
Unsafe class class1
{
// You can use pointers here!
}
Or only some class members can be declared as unsafe:
Class class1
{
// Pointer
Unsafe int * PTR;
Unsafe void mymethod ()
{
// You can use pointers here
}
}
The same applies to other members such as the constructor and the properties.
To declare unsafe local variables in a method, you have to put them in unsafe blocks as the following:
Static void main ()
{
// Can't use pointers here
Unsafe
{
// You can declare and use pointer here
}
// Can't use pointers here
}
You can? T declare local pointers in? Safe? Method in the same way we used in declaring global pointers, we have to put them in an unsafe block.
Static void main ()
{
Unsafe int * ptri; // wrong
}
If you got too excited and tried to use unsafe then when you compile the code just by using
CSC test. CS
You will experience the following error:
Error cs0227: Unsafe code may only appear if compiling with/unsafe
For compiling Unsafe code use the/unsafe
CSC test. CS/unsafe
In vs.net go to the project property page and in? Configuration Properties> build? Set allow unsafe code blocks to true.
After we knew how to declare a block as unsafe we shoshould now learn how to declare and use pointers in it.
Declaring pointers
To declare a pointer of any type all what you have to do is to put? *? After the type name such
Int * ptri;
Double * ptrd;
Note: If you used to use pointer in C or C ++ then be careful that in C # int * ptri, I ;? *? Applies to the type itself not the variable so? I? Is a pointer here as well, same as arrays.
Void pointers
If you want to declare a pointer, but you do not wish to specify a type for it, you can declare it as void.
Void * ptrvoid;
The main use of this is if you need to call an API function than require void * parameters. Within the C # language, There isn? T a great deal that you can do using void pointers.
Using pointers
Using pointers can be demonstrated in the following example:
Static void main ()
{
Int var1 = 5;
Unsafe
{
Int * ptr1, ptr2;
Ptr1 = & var1;
Ptr2 = ptr1;
* Ptr2 = 20;
}
Console. writeline (var1 );
}
The operator? &? Means? Address ?, Ptr1 will hold the address of var1, ptr2 = ptr1 will assign the address of var1, which ptr1 was holding, to ptr2. using? *? Before the pointer name means? The content of the address ?, So 20 will be written where ptr2 points.
Now var1 value is 20.
Sizeof Operator
As the name says, sizeof operator will return the number of bytes occupied of the given data type
Unsafe
{
Console. writeline ("sbyte: {0}", sizeof (sbyte ));
Console. writeline ("Byte: {0}", sizeof (byte ));
Console. writeline ("short: {0}", sizeof (short ));
Console. writeline ("ushort: {0}", sizeof (ushort ));
Console. writeline ("int: {0}", sizeof (INT ));
Console. writeline ("uint: {0}", sizeof (uint ));
Console. writeline ("LONG: {0}", sizeof (long ));
Console. writeline ("ulong: {0}", sizeof (ulong ));
Console. writeline ("char: {0}", sizeof (char ));
Console. writeline ("float: {0}", sizeof (float ));
Console. writeline ("Double: {0}", sizeof (double ));
Console. writeline ("decimal: {0}", sizeof (decimal ));
Console. writeline ("bool: {0}", sizeof (bool ));
// Did I miss something ?!
}
The output will be:
Sbyte: 1
Byte: 1
Short: 2
Ushort: 2
INT: 4
Uint: 4
Long: 8
Ulong: 8
CHAR: 2
Float: 4
Double: 8
Decimal: 16
Bool: 1
Great, we don? T have to remember the size of every data type anymore!
Casting pointers
A pointer actually stores an integer that represents a memory address, and it? S not surprising to know that you can explicitly convert any pointer to or from any integer type. The following code is totally legal.
Int x = 10;
Int * PX;
Px = & X;
Uint y = (uint) Px;
Int * py = (int *) y;
A good reason for casting pointers to integer types is in order to display them. console. write () and console. writeline () methods do not have any overloads to take pointers. casting a pointer to an integer type will solve the problem.
Console. writeline (? The address is :? + (Uint) Px );
As I mentioned before, it? S totally legal to cast a pointer to any integer type. But does that really mean that we can use any integer type for casting, what about overflows? On a 32-bit machine we can use uint, long and ulong where an address runs from zero to about 4 billion. and on a 64-bit machine we can only use ulong. note that casting the pointer to other integer types is very likely to cause and overflow error. the real problem is that checked keyword doesn? T apply to conversions involving pointers. for such conversions, exceptions wont be raised when an overflow occur, even in a checked context. when you are using pointers. net Framework will assume that you know what you? Re doing and you? Ll be happy with the overflows!
You can explain icitly Convert Between pointers pointing to different types. For example:
Byte abyte = 8;
Byte * pbyte = & abyte;
Double * pdouble = (double *) pbyte;
This is perfectly legal code, but think twice if you are trying something like that. in the above example, the double value pointed to by pdouble will actually contain a byte (which is 8), combined by an area of memory contained a double, which surely won? T give a meaningful value. however, you might want to convert between types in order to implement a union, or you might want to cast pointers to other types into pointers to sbyte in order to examine individual bytes of memory.
Pointers Arithmetic
It? S possible to use the operators +,-, + =,-=, ++ and -- with pointers, with a long or ulong on the right-hand side of the operator. while it? S not permitted to do any operation on a void pointer.
For example, suppose you have a pointer to an int, and you want to add 1 to it. the compiler will assume that you want to access the following int in the memory, and so will actually increase the value by 4 bytes, the size of Int. if the pointer was pointing to a double, adding 1 will increase its value by 8 bytes the size of a double.
The general rule is that adding a number X to a pointer to type T with a value p gives the result P + x * sizeof (t ).
Let? S have a look at the following example:
Uint u = 3;
Byte B = 8;
Double D = 12.5;
Uint * Pu = & U;
Byte * pb = & B;
Double * Pd = & D;
Console. writeline ("before operations ");
Console. writeline ("value of PU:" + (uint) Pu );
Console. writeline ("value of Pb:" + (uint) Pb );
Onsole. writeline ("value of PD:" + (uint) PD );
PU + = 5;
Pb-= 3;
PD ++;
Console. writeline ("/nafter operations ");
Console. writeline ("value of PU:" + (uint) Pu );
Console. writeline ("value of Pb:" + (uint) Pb );
Console. writeline ("value of PD:" + (uint) PD );
The result is:
Before operations
Value of PU: 1242784
Value of Pb: 1242780
Value of PD: 1242772
After Operations
Value of PU: 1242804
Value of Pb: 1242777
Value of PD: 1242780
5*4 = 20, where added to Pu.
3*1 = 3, where subtracted from Pb.
1*8 = 8, where added to PD.
We can also subtract one pointer from another pointer, provided both pointers point to the same date type. this will result a long whose value is given by the difference between the pointers values divided by the size of the type that they represent:
Double * pd1 = (double *) 12345632;
Double * Pd2 = (double *) 12345600;
Long L = pd1? Pd2; // gives 4 = 32/8 (sizeof (double ))
Note that the way of initializing pointers in the example is totally valid.
Pointers to structs and Class Members
Pointers can point to structs the same way we used before as long as they don? T contain any reference types. The compiler will result an error if you had any pointer pointing to a struct containing a reference type.
Let? S have an example,
Suppose we had the following struct:
Struct mystruct
{
Public long X;
Public double D;
}
Declaring a pointer to it will be:
Mystruct * pmystruct;
Initializing it:
Mystruct = new mystruct ();
Pmystruct = & mystruct;
To access the members:
(* Pmystruct). x = 18;
(* Pmystruct). d = 163.26;
The syntax is a bit complex, ISN? T it?
That? S why C # defines another operator that allows us to access members of structs through pointers with a simpler syntax. The operator? Pointer member access operator? Looks like an arrow, it? S a dash followed by a greater than sign:->
Pmystruct-> X = 18;
Pmystruct-> d = 163.26;
That looks better!
Fields within the struct can also be directly accessed through pointer of their type:
Long * PL = & (mystruct. X );
Double * Pd = & (mystruct. D );
Classes and pointers is a different story. We already know that we can? T have a pointer pointing to a class, where it? S a reference type for sure. The Garbage Collector doesn? T keep any information about pointers, it? S only interested in references, so creating pointers to classes cocould cause the Garbage Collector to not work probably.
On the other hand, Class Members cocould be value types, and it? S possible to create pointers to them. but this requires a special syntax. remember that class members are embedded in a class, which sets in the heap. that means that they are still under the control of the garbage collector, which can at any time decide to move the class instance to a new location. the garbage collector knows about the reference, and will update its value, but again it? S not interested in the pointers around, and they will still be pointing to the old location.
To avoid the risk of this problem, the compiler will result an error if you tried to create pointers pointing to class members in the same way we are using up to now.
The way around this problem is by using the keyword? Fixed ?. It marks out a block of code bounded by braces, and notifies the Garbage Collector that there may be pointers pointing to members of certain class instances, which must not be moved.
Let? S have an example,
Suppose the following class:
Class myclass
{
Public long X;
Public double D;
}
Declaring pointers to its members in the regular way is a compile-time error:
Myclass = new myclass ();
Long * PX = & (myclass. X); // compile-time error.
To create pointers pointing to class members by using fixed Keyword:
Fixed (long * PX = & (myclass. X ))
{
// Use * PX here only.
}
The variable * PX is scoped within the fixed block only, and tells the Garbage Collector that not to move? Myclass? While the code inside the fixed block.
Stackalloc
The keyword "stackalloc" commands. net runtime to allocate a certain amount of memory on the stack. it requires two things to do so, the type (value types only) and the number of variables you? Re allocating the stack for. For example if you want to allocate enough memory to store 4 floats, you can write the following:
Float * ptrfloat = stackalloc float [4];
Or to allocate enough memory to store 50 shorts:
Short * ptrshort = stackalloc short [50];
Stackalloc simply allocates memory, it doesn? T initialize it to any value. The advantage of stackalloc is the ultra-high performance, and it? S up to you to initialize the memory locations that were allocated.
A very useful place of stackalloc cocould be creating an array directly in the stack. while C # had made using arrays very simple and easy, it still suffers from the disadvantage that these arrays are actually objects instantiated from system. array and they are stored on the heap with all of the overhead that involves.
To create an array in the stack:
Int size;
Size = 6; // we can get this value at run-time as well.
Int * int_ary = stackalloc int [size];
To access the array members, it? S very obvious to use * (int_ary + I), where? I? Is the index. But it won? T be surprising to know That it? S also possible to use int_ary [I].
* (Int_ary + 0) = 5; // or * int_ary = 5;
* (Int_ary + 1) = 9; // accessing member #1
* (Int_ary + 2) = 16;
Int_ary [3] = 19; // another way to access members
Int_ary [4] = 7;
Int_ary [5] = 10;
In a usual array, accessing a member outside the Array bounds will cause an exception. But when using stackalloc, you? Re simply accessing an address somewhere on the stack; writing on it cocould cause to encrypt upt a variable value, or worst, a return address from a method currently being executed.
Int [] ary = new int [6];
Ary [10] = 5; // exception thrown
Int * ary = stackalloc int [6];
Ary [10] = 5; // The address (ary + 10 * sizeof (INT) had 5 assigned to it.
This takes us to the beginning to the article; using pointer comes with a cost. You have to be very certain of what you? Re doing, any small error cocould cause very strange and hard to debug run-time bugs.
Conclusion
Microsoft had chosen the term? Unsafe? To warn programmers of the risk they will go throw After typing that word. using pointers as we had seen in this article has a lot of advantages from flexibility to high performance, but a very small error, even a simple typing mistake, might cause your entire application to crash. worst, this cocould happen randomly and unpredictably, and will make debugging a very harder task to do.
-ArticleMardawi