You are not checking if head is NULL before accessing its data.
In the first code snippet there is a check that validates that head is not null before accessing its data.