Page 1 of 1

Memory Management

Posted: Thu Oct 21, 2010 2:08 pm
by ayushv
I'm a newbie to Chipmunk and trying to use it for the first time in an iPhone game. Would like a few clarifications on the Memory allocation and release of the various structs. I went over Alexandre Gomes' tutorial on getting started with Chipmunk, but in his example code none of the structs are every released / deallocated. Wont this lead to a memory leak at some stage?

1) Assume a cpShape is allocated and initialized (eg using cpCircleShapeNew()) and attached to a cpBody. After attaching, if we free the shape using cpShapeFree() then would this affect the behaviour of the cpBody?

2) Would calling cpSpaceFree() on the space also free up all the attached bodies / shapes / joints to that space?

I'm confused regarding how the reference count of each struct is affected when it is attached / removed to another struct ... please shed some light on this.

Re: Memory Management

Posted: Thu Oct 21, 2010 3:07 pm
by slembcke
As a C library, Chipmunk doesn't do any memory management or even simple ref counting beyond providing allocation and destruction functions. The intention is that if you are a C/C++ developer, you should already be aware of how to manage memory. If you are using a language with some form of garbage collection, Chipmunk splits alloc/init and destroy/free into separate functions so you can wrap it however you need.

When freeing an object you do have to be careful that nothing else has a reference to it (dangling pointers). Shapes and joints have a reference to the bodies they were attached to, so you have to free them before the bodies that they reference. Similarly, don't free a shape, joint or body before removing it from a space. Unless I'm forgetting something, those are really the only gotchas.