Testing Input Buffer Overflow

For example, if I enter more than 10 characters, why doesn't it throw an exception or error? would you get getline login?

int main() { char c[10]; while (cin >> c) { cout << c << endl; } } 
+1
source share
2 answers

Why doesn't it throw an exception or error?

Buffer overflows are an example of undefined behavior. The behavior is literally undefined: if you overflow the buffer, there is no guarantee what your program will do. This does not create an exception, because it will require many relatively expensive checks even in the correct code, and in C ++ the general philosophy is that you do not pay for what you do not need.

If you avoid raw arrays and raw (unthinkable) pointers and use the containers, strings, and algorithms of the C ++ standard library, you can easily avoid most situations that can lead to buffer overflows.

Do you get getline input instead?

You can use std::getline , which allows you to extract the "string" of characters in std::string , or you can use >> and extract directly to the std::string object, depending on what exactly you want to extract.

+6
source

There are tools that try to identify these problems. Examples of this are valgrind and GuardMalloc. In addition, msc allows you to specify build parameters that can identify such problems.

note also that different compilers emit different instructions based on your program and different instructions when optimized or not. this means that the consequences may exist in some assemblies and may not exist in others.

Sometimes I test my programs using the tools / methods that I mentioned. I also use more dynamic allocations in unit tests to make it easier to detect failure cases when starting programs using these tools.

if you come from java or another language that combines smart arrays: this is not how c programs are interpreted by the compiler, and not how they are presented in memory. instead, we usually use the appropriate containers in C ++. they will discover many of these problems. for example, std::vector may throw if you are trying to access an invalid element.

luck

0
source

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


All Articles