This question is out of my expertise. How do you recover, midstream, from a stack overflow overrun in “C”?
Where you are using a character variable declared as char string[12]
, and you move 12
characters to where you only have space for 11
characters. How do you detect a stack overflow overrun midstream? If you do detect an overrun, how do you fix the problem and carry on as normal?
The way I’m doing it is this:
character dform[12];
strcpy(dform,"june-11-2024"); when it should have been strcpy(dform,"jun-11-2024")
checkdate(dform); /// you have just invoked a stack buffer overrun, as you've passed on into a subroutine.
/// dform is only suppose to hold 11 characters and not 12 characters.
//// the 12th character causes the stack buffer overrun.
How do I detect it midstream, and if so, fix the problem midstream and then carry on with business as normal from within a subroutine and then pass back the corrected value.
Have tried many work arounds with no success. But want to nip it in the bud and then fix it and carry on. (It reminds me of C#’ exception handling capability.)
5
You don’t. It’s fatal.
dform
holds 12 characters including the trailing null, and by that same token you’ve written 13. Some other piece of the code may well have been storing something important in that following byte, and once you have overwritten it, there’s no way of knowing what it was. And you can readily imagine scenarios where the consequences of writing zero over a single byte are arbitrarily bad (e.g. it contained bool avert_global_armageddon = true;
.)
If the following byte happens to be on an unmapped page, it’s theoretically possible on some systems to catch the SIGSEGV signal and recover, as in that case no data was actually overwritten. But that is actually very unlikely for a bug like you describe.
If you know how to detect an overrun, then do it before the access in question, and if you determine that an overrun would occur, don’t do it!
If by some means you do determine after the fact that something like a buffer overrun occurred, you need to abort the program immediately (e.g. abort()
). Continuing to execute might do more damage (e.g. corrupting more memory or data) or allow an attacker to carry out an exploit.
you are using a character variable declared as charstring[12], and you move 12 character; where you only have space for 11 characters. Now, How do you detect a stack overflow overrun midstream.
No point in detecting overflow after it has happened, because then your program is already in an unpredictable state due to invoking undefined behavior.
Consider:
if (strlen("june-11-2024") < sizeof dform - 1) {
strcpy(dform,"june-11-2024");
} else {
// handle error here
}
Or use a bigger buffer size, or allocate memory dynamically with malloc()
and family.