check return value of calloc call and remove duplicated code