When allocating memory for an object in C++ using new
, you must later deallocate it with delete
or you will likely have a memory leak. In C, malloc
corresponds with free
.
When it comes to Box2D, world.CreateBody
and world.DestroyBody
handle b2Body
creation and clean up for you. Additionally, you do not need to allocate the b2BodyDef
, b2FixtureDef
, and b2PolygonShape
objects on the heap using new
. Instead, create them on the stack like so:
b2BodyDef bodyDef;
bodyDef.position.Set(center.x + size/2, center.y + size/2);
b2Body* body = world.CreateBody(&bodyDef);
b2PolygonShape box;
box.SetAsBox(size / 2, size / 2.0f);
b2FixtureDef fixtureDef;
fixtureDef.shape = &box;
fixtureDef.friction = 0.3f;
body->CreateFixture(&fixtureDef);
Notice that no usage of new
is necessary.
Finally, be careful when using SetUserData
to store pointers to your own custom data in b2Body
and b2Fixture
using new
. You must iterate over the body's fixtures and call delete
on any user data that you stored in there.
You can learn more about the C++ stack vs. heap here: https://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap