Fixed some memory issues and a few problems around cleaning up the
shared memory segment.

TODO: semaphores