Fix segfaults, memory leaks, etc