Fixed memory allocation bugs