Fix all memory-related bugs