Fix various memory problems (bug 5766).