world.createBody() not giving a valid pointer.

Hello again. So I had just gotten to the point where I can read in a level file and generate the world for the player to run around in and it was time to move on to triggers that would allow the old level to be purged and the new one to be loaded. Sounded easy since I pretty much had everything I need working... or so I thought.

The problem is that when I attempt to add new bodies to the currently existing world in the above mentioned scenario world.createBody(BodyDef) always returns null! During my quest to track down the issue I decided to review my construction and destruction of the classes I use to wrap bodies and found something else that is quite odd and may be related.

When a new level is loaded it first purges all the old collision data by calling the dispose method on all the objects wrapping Jbox2D bodies. The code for this is simply the following:
Code:
  //In this case 'this.body' is the pointer stored from the constructor's call to 'refWorld.createBody(BodyDef)'
  this.refWorld.destroyBody(this.body);
  this.body = null;
  this.refWorld = null;


Works like a charm. The trouble is that when I double checked this by manually cycling through all of the bodies in the world using:
Code:
while(b != null)
    {
    Body next =  b.getNext();
    world.destroyBody(b);
    b = next;
    }

... it still found and removed the exact same number of bodies as had already been destroyed using the disposal method above. Just to be sure what objects I was looking at, I checked the hashes of all the bodies and it appears that the ones I get from world.createBody(BodyDef) are not the ones being found in the above loop. They are, however, the ones being destroyed in the dispose method. It seems that there are in fact two sets of bodies floating around in the world! Is this supposed to happen? Am I doing something wrong here? More importantly, is this somehow related to the fact that I can't seem to add new bodies to the world at a later point?

For reference, I'm using JDK 1.7 and JBox2D 2.1.2.2
Where do you get the "b" variable? from the world's body list?
Whoops, sorry.

Yes, 'b' is from world->getBodyList(). And just to be sure, I checked the hash values of all the world references to make sure they were the same. They were.
Ok, well this is probably because the world is locked when you try to destroy the bodies. You cannot add or remove bodies from the world while it's stepping, which means you can't do that during calls to the contact listener.
Yep, that was it. Makes sense when I think about it really. It just took some time for me to realize that it was happening during a step due to some very non-linear code.

Thanks!

Original thread: https://box2d.org/forum/viewtopic.php?t=8179