fix memory leaks and other minor things

- free the allocated resources in both the state machine and the
  message queue.
- check for machine_finished flag before creating and sending
  a new EXIT message on the queue.