由于内存而失败时如何处理realloc? [英] How to handle realloc when it fails due to memory?

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

问题描述

问题说明了一切,但这里有一个例子:

Question says it all but here is an example:

typedef struct mutable_t{
    int count, max;
    void **data;
} mutable_t;


void pushMutable(mutable_t *m, void *object)
{
    if(m->count == m->max){
        m->max *= 2;
        m->data = realloc(m->data, m->max * sizeof(void*));
    }
    // how to handle oom??
    m->data[m->count++] = object;
}

如何处理内存不足而不是所有数据都为 NULL?

How can I handle running out of memory and not NULL out all of my data?

edit - 让我们假设有一些可以完成的事情,例如在某处释放一些内存或至少告诉用户你不能这样做 - 你内存不足".理想情况下,我希望将分配的内容留在那里.

edit - let's assume there is something which could be done e.g. free up some memory somewhere or at least tell the user "you can't do that - you're out of memory". Ideally I would like to leave what was allocated there.

推荐答案

标准技术是引入一个新变量来保存 realloc 的返回值.然后,如果成功,您只会覆盖您的输入变量:

The standard technique is to introduce a new variable to hold the return from realloc. You then only overwrite your input variable if it succeeds:

tmp = realloc(orig, newsize);
if (tmp == NULL)
{
    // could not realloc, but orig still valid
}
else
{
    orig = tmp;
}

这篇关于由于内存而失败时如何处理realloc?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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