Added error check for malloc