Adds NULL checks for malloc returns