Added error handling for malloc failure