Bug in allocation of freed entities

Added a test that will free an entity, and then allocate again. This would give a segmentation fault.

Added a fix to the allocation algorithm.