Fixed several issues with memory allocation