Buffer array overflow for loop in c

When the program crashes in case of buffer overflow

#include<stdio.h> #include<stdlib.h> main() { char buff[50]; int i=0; for( i=0; i <100; i++ ) { buff[i] = i; printf("buff[%d]=%d\n",i,buff[i]); } } 

What happens to the first 50 bytes assigned when the program crashes?

I see in my UBUNTU with gcc a.out it crashes when I 99

 >> buff[99]=99 *** stack smashing detected ***: ./a.out terminated Aborted (core dumped) << 

I would like to know why this is not a failure when doing a job in buff [51] in a for loop?

+6
source share
2 answers

This is undefined behavior . You can never predict when (or, if at all) it will work, but you cannot rely on it to “fail” and the application code.

Reasoning

The rationale is that in c arrays there is no compilation or runtime "index from linked check". This is present in STL vectors or arrays in other higher-level languages. Therefore, whenever your program accesses memory outside the allocated range, it depends on whether it simply distorts another field in your program stack or affects the memory of another program or something else, so it is impossible to predict a failure that only occurs in extreme cases. It is only a failure in a state that causes the OS to intervene or when it no longer remains possible for your program to function correctly.

Example

Say that you were inside the function call, and right next to your array was the address RETURN, that is, the address that your program uses to return to the function from which it was called. Suppose you mess this up, and now your program is trying to return to a damaged value that is not a valid address. Consequently, in such a situation he would have collapsed.

The worst happens when you tacitly modify a different field value and don't even find out what was wrong if there was no failure.

+13
source

Since it seems like you pushed a buffer onto the stack, the application may crash the first time you rewrite an instruction that needs to be executed, perhaps somewhere in the for loop code ... at least that it should be in theory .

+1
source

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


All Articles