fixed defragment_memory function