Fix bugs in memory allocation