FIX: Several allocation errors and memory leaks found by Dr. Memory