Fixed bugs with memory allocation