Possible Duplicate:
What is a stack overflow error?
Can any one tell me how and why stack overflow and heap overflow actually occur in programs, and how to overcome stack overflow in programming - how to avoid it?
void stack_overflow(const char *x)
{
char y[3];
strcpy(y, x);
}
void heap_overflow(const char *x)
{
char *y = malloc(strlen(x));
strcpy(y, x);
}
Both functions trample beyond the allocated space.
If you call stack_overflow("abc")
, it copies 4 characters (including the null) into space allocated for 3 characters. What happens after that depends on where the damage was done. The variable y
is on the stack, so it is stack overflow.
Regardless of how you call heap_overflow()
, it asks for one too few bytes from the heap and then writes beyond the end. What's insidious about that is that some of the time - even most of the time - it will seem to work because the heap system allocates more space than you request. However, you might trample on control data, and then all bets are off.
The heap overflow is very small, and hard to detect. The stack overflow can be small (non-existent if the passed string is short enough) or dramatic. You normally get more dramatic effects when you write further beyond the allocated space, but any writing beyond the allocated space leads to undefined behaviour - anything could happen.
You ensure there are no problems by knowing how big the object you are copying is and how much space there is to receive it, and by making sure that you do not copy more material than there is space. Always, every time.
"stack overflow" is different from "stack-based buffer overflow". The former is due to too deep activation records, for example an unstopping recursive call. The latter is a software bug due to insufficient boundary check, which is the most frequently exploited vulnerability.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With