added NULL checks after malloc