Fix various memory leaks and invalid memory usages