Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When a class dynamically allocates itself at constructor, why does stack overflow happen instead of std::bad_alloc?

I made a class that recursively creates itself using new (just for fun!), expecting that this will throw std::bad_alloc due to infinite dynamic allocation (heap overflow). But stack overflow happened instead of std::bad_alloc. Why does this happen?

class Overflow
{
private:
    Overflow* overflow;

public:
    Overflow()
    {
        overflow = new Overflow();
    }
};

int main()
{
    Overflow overflow_happens; // stack overflow happens instead of std::bad_alloc exeption
}

@Caleth asked what happens if I change new Overflow() to new Overflow[100000], and this gave me std::bad_alloc. According to the answers, shouldn't this also give me stack overflow?

like image 704
ownfos Avatar asked Jun 11 '19 13:06

ownfos


2 Answers

The stack overflow is happening because you have infinite recursion. Calling Overflow() causes you to call Overflow() again and again and again. Those function calls need to go on the stack. Since your stack is smaller than your heap you'll run out of stack space for all of the those constructor calls before you run out of memory for all of the objects you are creating.

like image 156
NathanOliver Avatar answered Nov 12 '22 13:11

NathanOliver


Because you are recursively calling the constructor, a method, repeatedly. The method calls get pushed to the call stack. Since the stack size is much smaller than the available heap, the call stack overflows before the heap runs out.

like image 4
Avin Kavish Avatar answered Nov 12 '22 15:11

Avin Kavish