Fix various memory allocation bugs and resource leaks.