Fix SEGFAULT and space leak

Thanks! =)