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?