Can strong types prevent buffer overflows?

Do strong types in this case char prevent buffer overflows?

char a[100] char b[100] strcpy(a,unknownFunction); // unknownFunction could overflow b // since its length is unknown strcpy(b,a); // can b still overflow a with its now, // potentially overflowed size? 
+4
source share
5 answers

Not. strcpy() just continues until it finds a null terminator ( '\0' ). If b[] does not contain one, it will simply walk through random memory until it finds it.

+9
source

C does not have a strong type system.

C ++ is a little stronger typed, but in fact it is not a real strong type system, since it has reinterpret_cast .

For a type system that prevents buffer overflows, type information must either (1) indicate an arbitrarily long string, or (2) encode the length of the buffer in the type itself. In addition, the type estimation system must ensure that the buffer length is less than or equal to the conversions.

Edit:

With some caution and neglecting the capabilities of cast-tastic C ++, you can write a “reasonably strong” buffer class without overflow in C ++. However, this is not strictly typified for a general definition of the term, since you can try to access the buffer at an invalid point and still compile it. Someone is much better at templates than I could write a really customized SafeBuffer template.

Here is my cut:

 template<int Length> class SafeBuffer { unsigned char[Length]; public: unsigned char& operator[](int index); //when implemented, throws exception on out-of-range access. }; SafeBuffer<10> buf, foo; SafeBuffer<9> bar; buf = foo; //pass buf = bar; //compile-time error. buf[100]; //compiles, but generates error at runtime. 

Note that we use a template type evaluation system to cause a compilation error buf = bar . This is an example of what a strongly typed system can do (also note that casts can 100% destroy typing in C ++).

+5
source

The argument type strcopy() is char * . This means that as soon as you pass your arrays to strcpy() , it has no way of knowing that these are arrays of fixed size. As for the function, they are just pointers, and they will keep the copy elements until they find \0 in b .

The main thing is that when a function accepts a pointer, which is a pointer, it cannot determine whether it is a pointer to a single object, a pointer to a dynamically allocated buffer, or a fixed-size array allocated to the stack.

So the answer is no.

+3
source

it can still overflow, strcpy stops when it finds NUL to prevent overflow, you should use strlcpy or strncpy

 // using strlcpy strlcpy(a, unknownFunction, 100); // using strncpy strncpy(a, unknownFunction, 100); a[99] = 0; // strncpy doesn't NUL-terminate the result 
+1
source

In general, strncpy is a safer alternative to strcpy .

0
source

All Articles