C++ object pool: program crashes when using malloc

599 views Asked by At

I am trying to make a simple object pool and i cant get it to work . My code crashes when using malloc to allocate space for a dynamic array of template's type

my code:

template <class cl>
class ObjectPool{
public:
    gltAtlasRenderer* br;
    cl* items;
    int SIZE,texid;

    void Innit(int size,int texidi)
    {
        SIZE=size;
        items=(cl*)malloc(sizeof(cl)*SIZE);->>>>>>>>>>HERE MY APP CRASHES
        /*br=new gltAtlasRenderer(SIZE,false,1);
        texid=texidi;
        for(int c=0;c<SIZE;c++)items[c].alive=false;
        */
    }
    void Update(Arena*  arena)
    {
        for(int c=0;c<SIZE;c++)
        {
            if(!items[c].alive)continue;
            items[c].Update(arena);
        }
    }
    void Render()
    {
        br->RenderStart();
        for(int c=0;c<SIZE;c++)
        {
            if(!items[c].alive)continue;
            items[c].Render(br);
        }
        br->RenderStop(texid);
    }
};

All the examples that i found in the web are using fixed arrays and vectors ,but i need the array to be allocated at runtime.

EDIT: This is how i create it:

ObjectPool<Enemie1>* enemies1;
void Innit()
{
         enemies1->Innit(size,texid);
}

I know that is crashing in that line cause if i commend it it doesnt crashes

2

There are 2 answers

1
Šimon Tóth On BEST ANSWER

This will not work:

ObjectPool<Enemie1>* enemies1;
void Innit()
{
         enemies1->Innit(size,texid);
}

You need to allocate the memory before using it, like this:

ObjectPool<Enemie1>* enemies1;
void Innit()
{
         enemies1 = new ObjectPool<Enemie1>;
         enemies1->Innit(size,texid);
}
0
Dirk Holsopple On
ObjectPool<Enemie1>* enemies1; //This is uninitialized
void Innit()
{
     enemies1->Innit(size,texid); //This calls a method on an uninitialized pointer
}

In the Innit method when you assign the result of malloc to one of the members you are assigning through an invalid pointer which causes a crash.

Change it to this.

ObjectPool<Enemie1> enemies1;
void Innit()
{
     enemies1.Innit(size,texid);
}