简体   繁体   中英

Buffer overflow - The changes of variables

void go()
{
    //{1}
    char buffer[2];
    gets(buffer);
    //{2}
    cout << allow;
}

I tried to run the procedure above in 2 cases:

-1st: I declare "int allow;' at position 1

-2nd: I declare "int allow;' at position 2

In both cases, when i tried to enter the string "123" (without the quotation marks), the allow's value was 51. However, as I read about the memory layout, only in the first case, the position of "allow" in the stack is before buffer, which means that when the string is longer than the buffer, the value of "allow" is changed.

Then, I tried to declare "char sth[10]" in both position. This time, only when I declared sth in first position, the value of it was changed.

Can anyone explain what happened?

Since changing allow via overflow is Undefined Behavior , the compiler might even not have a variable allow at all and change your code to cout << 0 instead when compiling with optimization. This is not a valid way to check for overflow, regardless of where you put allow .

To emphasize: All changes of allow you observe are the result of UB. There are no guarantees on this in the standard what so ever. You can go ahead and speculate on why you see this output today, on you system, with this very toolchain, but the outcome might change to anything (like your program moving your lawn or stealing the crown jewels) for any reason.

Indeed, there is no way to use gets safely. This is why it is removed in both the current C++ and C standard.

You can use std::string and std::getline instead:

string buffer;
std::getline(std::cin, buffer);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM