Matthew
Matthew

Reputation: 31

Access violation malloc and inheritance C++

I have a GameObject which contains an array of Shapes(assigned via malloc). Shapes have a list of Points in them and can be inherited to be Polygons. Init code:

    GameObject g1(true, true);
    Color c(0, 0, 1, 0);
    Point p(100, 100, 0);
    Polygon s(p, c);
    s.addPoint(p);
    s.createRegularShape(4, 50.0f);
    g1.addShape(s);

This is in the header.

    Shape* shapes;

This is where it breaks (when I try to access the data)

void GameObject::draw(unsigned int gameTime)
{
    if(visible)
    {
        for(int i = 0; i < count; i++)
        shapes[i].draw();//Access violation happens here
    }
}

This is how I add the Shape to the Shape array.

void GameObject::addShape(Shape const& shape)
{
    if(count == size)
    {
        size += 4;
        shapes = (Shape*)realloc(shapes, sizeof(Shape) * size);
    }
    shapes[count] = shape;
    count++;
}

This is where I allocate memory for the Shape. This is called in the constructor when we need to allocate memory to the shapes array.

void GameObject::clearShapes(int size)
{
    if(count > 0)
        free(shapes);
    shapes = (Shape*)malloc(sizeof(Shape) * size);
    count = 0;
    GameObject::size = size;
}

So basically, what am I doing wrong? How am I getting an access violation from this code? The data seems to all be the correct size and be legitimate.

Upvotes: 1

Views: 628

Answers (1)

Nikos C.
Nikos C.

Reputation: 51910

When you use malloc(), the constructor of the objects is not run. As you can guess this can create all sorts of problems. Use new instead.

Do not use malloc() in C++ to create objects.

This:

Shape* shapes;

is an array of Shape objects, not an array of Shape pointers. That means the initial contents:

shapes = (Shape*)malloc(sizeof(Shape) * size);

and later:

shapes = (Shape*)realloc(shapes, sizeof(Shape) * size);

are not constructed. So when you later do:

shapes[count] = shape;

The assignment operator is called on shapes[count], which is a non-constructed Shape. It looks to me like you're waaay into undefined behavior here. Any kind of runtime error is possible.

Get rid of malloc() and realloc(), and instead use an std::vector<Shape> where you push_back() new Shapes. If you want to keep doing it with a plain dynamic array, then you should switch to an array of pointers instead:

Shape** shapes;

And only hold Shape pointers in there. This of course requires refactoring of your program logic, and I don't see why you would want to keep using malloc() and realloc().

Upvotes: 2

Related Questions