C ++ and C # Security

I read the questions with the most votes and came across https://stackoverflow.com/q/4377512/627005 , where the accepted answer states that C has "minimal type security", C ++ has "better type security" and C # "has security type". Why is C # safer than C ++?

+6
source share
3 answers

C ++ inherits many C functions, so you can always do something unsafe if you want. It is only that if you use C ++ idiomatically, then you usually get type safety. There simply will absolutely nothing stop you if you decide to leave safe places.

C # applies a stronger type system and limits the use of C-style constructs (primarily pointer arithmetic) to marked “unsafe” regions, so you have better (= automatic) control over what is typical and what is not, t


Digression: It may be worth considering what “safe” means. A language is called safe if we can make sure that a particular piece of code is correct. In a statically typed language, this basically boils down to type checking: if we have an expression a + b , then we just check the types: int plus int equals int , fine; struct plus union does not make sense to compile the error.

The odd man in this setting is the dereference operator * : When we see *p , we can check that p is a pointer, but this is not enough to prove the correctness of the expression. The correctness of the code depends not only on the type p , but also on its value. This underlies the insecurity of C and C ++.

Here are two examples to illustrate:

 // Example #1 void print_two(const char * fmt) { double d = 1.5; unsigned int n = 111; printf(fmt, d, n); } // Example #2 unsigned int get_int(const char * p) { return *(unsigned int *)(p - 3); } 

In example # 1, the correctness of the code depends on the value specified at run time of the line pointed to by fmt . In example # 2, we have the following:

 unsigned int n = 5; double d = 1.5; const char * s = "Hello world"; get_int((char*)(&n) + 3); // Fine get_int((char*)(&d) + 3); // Undefined Behaviour! get_int(s + 5); // Undefined Behaviour! 

Again, just by looking at the get_int() code, we cannot determine whether the program will be correct or not. It depends on how the function is used.

A safe language will not allow you to write such functions.

+10
source

If you do not use /unsafe , only some unsafe type operation in C # is type casting - but it will throw an exception at the time of the throw. In C ++, reinterpret_cast and others. You may run into much bigger problems, such as access violations when dereferencing actual pointers.

+4
source

The short answer is that they wrote it.

The easy way out of this .net does not allow untyped variables, and it only allows operations defined for the type in question.

For more details, you need to read in CTS (Common Type System)

These were different languages, but still valid.

Compiler C is an accomplice.

The .Net compiler is a policeman .....

0
source

Source: https://habr.com/ru/post/902408/


All Articles