Fixed memory leaks

Fixed all memory leaks and other warnings found with the static analyzer.