Fix memory leaks

- Free or manage memory for strings
- Ensure that datatypes are closed when necessary

Fixes #136, #155