Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain stack overflow and heap overflow in programming with example? [duplicate]

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?

like image 451
Vishwanath Dalvi Avatar asked Jan 15 '11 17:01

Vishwanath Dalvi


2 Answers

Stack Overflow

void stack_overflow(const char *x)
{
    char y[3];
    strcpy(y, x);
}

Heap Overflow

void heap_overflow(const char *x)
{
    char *y = malloc(strlen(x));
    strcpy(y, x);
}

Analysis

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.

like image 132
Jonathan Leffler Avatar answered Oct 04 '22 17:10

Jonathan Leffler


"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.

like image 35
Infinite Avatar answered Oct 04 '22 18:10

Infinite