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