Minor tweaks and optimization, correct error handling for malloc failures