我们应该检查一下内存分配失败? [英] Should we check if memory allocations fail?

查看:110
本文介绍了我们应该检查一下内存分配失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了很多code的一个检查每当分配是由NULL指针。这使得code啰嗦了,如果它不能持续进行,只有当程序员有感而发,甚至不保证当地址空间耗尽时,程序不会崩溃。此外,如果程序不能让更多的分配,这将无法无论如何做它的功能吧?

I've seen a lot of code that checks for NULL pointers whenever an allocation is made. This makes the code verbose, and if it's not done consistently, only when the programmer felt like it, doesn't even ensure that the program won't crash when the address space runs out. Besides, if the program can't make more allocations, it wouldn't be able to do its function anyway, right?

所以我的问题是,是不是对于大多数程序最好不要在所有的检查,只是让程序崩溃,如果内存用完?至少code是更具可读性的方式。

So my question is, isn't it better for most programs not to check at all and just let the program crash if memory runs out? At least the code is more readable that way.

注意

我说的,关于现代计算机(至少2 GB的地址空间)中运行的桌面应用程序,而且大多数绝对不操作航天飞机,生命支持系统,或BP的石油平台。更重要的是我在谈论的是使用malloc,但从来没有真正去突破5 MB的内存使用的程序。

I'm talking about desktop apps that run on modern computers (at least 2 GB address space), and that most definitely don't operate space shuttles, life support systems, or BP's oil platforms. Most importantly I'm talking about programs that use malloc but never really go above 5 MB of memory usage.

推荐答案

经常检查返回值,但为清楚起见,这是常见的包装的malloc()在函数从未返回 NULL

Always check the return value, but for clarity, it's common to wrap malloc() in a function which never returns NULL:

void *
emalloc(size_t amt){
    void *v = malloc(amt);  
    if(!v){
        fprintf(stderr, "out of mem\n");
        exit(EXIT_FAILURE);
    }
    return v;
}

那么,以后你可以用

Then, later you can use

char *foo = emalloc(56);
foo[12] = 'A';

由于没有心虚。

这篇关于我们应该检查一下内存分配失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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