A few memory bugs fixed

Fixed a few memory bugs that did not consider null cases causing segmentation fault.