Remove unused variable.
Refactor to remove duplication of code responsibility.

Also checks that malloc returns successfully.