Improve memory allocations and eliminate memory leaks