memleak and segfault fixed