zeroes00
zeroes00

Reputation: 531

Stack overflow while allocating from heap

What exactly is happening here?

#include <boost/array.hpp>
#include <boost/assign/list_of.hpp>

struct Toy {
    int m_data[100000];
};

struct Box {
    Box()
        : m_toys(  boost::assign::list_of( Toy() )( Toy() )( Toy() )  )
    {}

    boost::array<Toy,3>   m_toys;
};

void main()
{
    Box* box = new Box; // This causes stack overflow
}

Upvotes: 3

Views: 197

Answers (3)

Ferruccio
Ferruccio

Reputation: 100658

The problem is the Toy() objects being passed to boost::assign::list_of(). These are temporary objects which are created on the stack before being copied to the Box object (which will be on the heap)

to avoid creating them on the stack, you could do this:

Box() : m_toys()
{
   Toy* t = new Toy;
   for (int i = 0; i < 3; ++i)
       m_toys.push_back(*t);
   delete t;
}

Upvotes: 7

Seva Alekseyev
Seva Alekseyev

Reputation: 61361

The stack overflow is happening in the Box() constructor. I'm not sure how does boost::assign work, but it looks like you're passing to it, as arguments, three temporary variables of type Toy. Constructed, as they are, on the stack.

Upvotes: 1

Alex Brown
Alex Brown

Reputation: 42872

The value

boost::assign::list_of( Toy() )( Toy() )( Toy() )

generates a (giant) temporary on the stack (woo!) that is passed to the constructor for toys.

Upvotes: 1

Related Questions