fixed the bug that caused the segmentation fault and added clean ups

for the allocated memory