Testing buffer overrun of input
For example, if i input characters greater than 10 why doesn't it throw an exception or error? would you get the input with getline instead?
int main()
{
char c[10];
while (cin &开发者_StackOverflow社区gt;> c)
{
cout << c << endl;
}
}
Why doesn't it throw an exception or error?
A buffer overflow is an example of undefined behavior. The behavior is literally undefined: if you overflow a buffer, there are no guarantees whatosever about what your program will do. This doesn't generate an exception because doing so would require lots of relatively costly checks even in correct code, and in C++ the general philosophy is that you don't pay for what you don't need.
If you avoid raw arrays and raw (non-smart) pointers and use the C++ Standard Library containers, strings, and algorithms, you can easily avoid most situations that would result in a buffer overflow.
Would you get the input with
getline
instead?
You can either use std::getline
, which allows you to extract a "line" of characters into a std::string
, or you can use >>
and extract into a std::string
object directly, depending on what, exactly, you want to extract.
there are tools which attempt to expose these issues. valgrind and GuardMalloc are examples of this. as well, msc allows you to specify build options which can expose such issues.
note also that different compilers emit different instructions based on your program, and different instructions when optimizing or not. this means the consequences may exist in some builds, and may not exist in others.
i occasionally test my programs using the tools/techniques i've mentioned. i also use more dynamic allocations in unit tests, in order to expose failure cases more easily when running programs with these tools.
if you're coming from java or another language which integrates smarter arrays: that's not how c programs are interpreted by the compiler, nor is it how they are represented in memory. instead, we typically use proper containers in c++. these will detect many of these issues. for example, a std::vector
may throw if you attempt to access an invalid element.
good luck
精彩评论