adding error handling for freeing memory when return values fail