Fix memory leaks and memory cleanup on exit

The commits in this pull request fix issues found by valgrind: memory leaks and bad cleanup. After the changes the valgrind summary is

```
==30453== LEAK SUMMARY:
==30453==    definitely lost: 0 bytes in 0 blocks
==30453==    indirectly lost: 0 bytes in 0 blocks
==30453==    possibly lost: 3,328 bytes in 16 blocks
==30453==    still reachable: 69,554 bytes in 723 blocks
==30453==         suppressed: 0 bytes in 0 blocks
```

Improvements are seen in definetly and indirectly lost categories which showed ~50/~700 bytes respectively in quick tests.

See individual commits for more comprehensible diffs.