Prevent segfault and memory leaks