Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stack vs buffer

What is the difference between buffer and stack? Is a buffer overflow and stack overflow the same thing?

Thank you.

like image 572
Farnaz Avatar asked Dec 21 '22 16:12

Farnaz


2 Answers

A stack overflow is usually caused by unbridled recursion (although it can be caused in the normal course of events if you don't have enough stack space for a normal level of function calls, such as with embedded systems, or even with limited recursion if the limits are too high). An example below:

void f (void) {
    f();
}
int main (void) {
    f();
    return 0;
}

In that example, the f() function very foolishly calls itself and, each time it does that, it allocates a stack frame, which will eventually lead to an overflow of the stack.

A buffer overflow, on the other hand, is caused by writing beyond the end of a buffer. They're often confused since a buffer overflow on the stack will often corrupt the stack but, technically, they're very different things. An example of stack-based buffer overflow is:

void f (void) {
    char str[10];
    strcpy (str, "This is far too long to fit");
}

This will probably corrupt the stack since you're trying to shove a 27-character string (28 bytes) into a space that's only 10 bytes in size.

But a buffer overflow doesn't necessarily have to be on the stack. If the buffer was allocated from the heap (say, with malloc), there's a good chance it will trash the memory arena instead, as per:

void f (void) {
    char *blk = malloc (10);
    if (blk != 0) {
        memset (blk, ' ', 100);
        free (blk);
    }
}

Similar to the previous example except the buffer overflow is not corrupting the stack. Rather it's writing beyond the end of the buffer in the heap.

like image 178
paxdiablo Avatar answered Jan 02 '23 09:01

paxdiablo


A buffer overflow is when you aren't checking the length of a buffer, or pass a non-terminated buffer to a function expecting one (specifically in C). You go past the end of the allocated buffer.

Buffer overflow:

char *foo = malloc(10); /* 10 bytes in our buffer */
char bar[] = "This is way bigger than 10 bytes"; 
strcpy(foo, bar);

A Stack overflow is when you use up all the stack memory. This is called by recursion, allocating too maky things on the stack.

Stack overflow:

int foo()
{
    int bar = 4;
    foo();
    return 1; /* we never get here, silly */
}
like image 24
Brian Roach Avatar answered Jan 02 '23 09:01

Brian Roach