Fix segfauls and unitialized

There were multiple causes of segmentation faults, which I tried to fix in this pull request. With these changes `valgrind` doesn't produce any error messages.