如果失败的malloc? [英] What if malloc fails?

查看:156
本文介绍了如果失败的malloc?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果一个的malloc 分配失败,我们应该再试一次?

If a malloc allocation fails, should we try it again?

在这样的:

char* mystrdup(const char *s)  
{
    char *ab = NULL;

    while(ab == NULL) {
        ab=(char*)malloc(strlen(s)+1);  
    }

    strcpy(ab, s);
    return ab;
}

是while循环的有效检查内存分配?

Is the while loop valid for checking the memory allocation?

推荐答案

在一般情况下,一个现代化的的malloc()实施将返回 NULL 只能作为一个绝对的最后手段,并试图再次肯定不会有帮助。这将帮助的唯一事情是的释放一些内存的,然后再次尝试。如果你的应用程序保存任何资源消耗,这将是一次释放他们,然后给它一个镜头。

In general, a modern malloc() implementation will return NULL only as an absolute last resort, and trying again will definitely not help. The only thing that will help is freeing some memory and then trying again. If your application holds any expendable resources, this would be the time to free them, and then give it another shot.

在某些环境中,一个有用的做法是分配的少量内存作为的应急基金的。如果的malloc()曾经确实的回报 NULL ,可以自由的应急基金,然后分配任何你需要的资源,以便能够处理错误,并优雅地退出。这是与旧的Macintosh工具箱编程时的普遍做法;如果的malloc()返回 NULL ,你可以使用这个空间来创建一个对话框退出之前报告的问题。

In some environments, a useful practice is to allocate a small amount of memory as a rainy-day fund. If malloc() ever does return NULL, you can free that rainy-day fund, and then allocate whatever resources you need to be able to handle the error and exit gracefully. This was a common practice when programming with the old Macintosh Toolbox; if malloc() returned NULL, you could use that space to create a dialog to report the problem before exiting.

这篇关于如果失败的malloc?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆