Check if references are null before freeing them.