Fix bugs in memory handling.