如何处理realloc的由于内存时失败? [英] How to handle realloc when it fails due to memory?
本文介绍了如何处理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;
}
我
该如何处理运行内存和NOT NULL所有我的数据?
How can I handle running out of memory and not NULL out all of my data?
编辑 - 假设有东西可以做如释放一些内存的地方,或者至少告诉用户:你不能这样做 - 你是内存不足。理想情况下,我想留下什么被分配在那里。
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屋!
查看全文