malloc在do while块中 [英] malloc in do while block
问题描述
我可以将malloc放入do ... while块中以确保成功分配吗?
Can I put malloc in do...while block to ensure successful allocation?
喜欢:
#define STR_SIZE 1024 * 1024
char *str;
do
str = (char *) malloc(STR_SIZE);
while ( !str );
推荐答案
它可能不起作用,因为 malloc
很少失败,资源耗尽时它也会失败,并且这些将不可用很快.
It probably won't work, because malloc
rarely fails, it fails when resources are exhausted, and these won't be available soon.
malloc
可以获取更多资源的唯一常见情况是,是否有其他大型进程释放大量内存,而这种情况很少发生,甚至可能永远不会发生.如果您关心这一点,请在循环中至少添加一个 malloc
真正失败并始终返回 NULL
的情况.
the only common case when malloc
could get more resources is if some other big process releases a lot of memory, and that seldom happens and may never happens; if you cared about that add at least a sleep
in your loop, and be prepared to handle the case when malloc
genuinely fails and always return NULL
.
更好的做法是测试 malloc
结果并退出并显示错误和错误消息,例如
The better practice is to test malloc
result and exit with failure and error message, e.g.
char* str = malloc(STR_SIZE);
if (!str) {
perror("malloc failed for str");
exit (EXIT_FAILURE);
}
每个程序都应处理 malloc
失败的情况(通常通过出现错误消息退出).
And every program should deal with the case when malloc
fails (usually by exiting with an error message).
许多程序调用 xmalloc
这个函数,当 malloc exit
-s或 abort
-scode>失败,并在成功后返回分配的区域
A lot of programs call xmalloc
a function which exit
-s or abort
-s when malloc
fails, and return the allocated zone when it succeeds
通过malloc失败明智地进行处理(这是在做一些事情才能继续执行)确实很困难.例如,某些程序可能 free
其他一些全局数据.实际上,这等于实现了一些专门的垃圾收集机制.某些服务器可能只是使当前请求失败(并且应该非常小心,释放该当前失败请求所使用的所有资源).
Dealing sensibly with a malloc failure (that is doing something to be able to continue execution) is really hard. Some programs might for instance free
some other global data. Actually this amounts to implement some specialized garbage collection mechanism. Some servers might just fail the current request (and should do that with great care, releasing all the resources used by that current failed request).
和 malloc
可能会真正失败.因此,您必须处理这种情况.
And malloc
can genuinely fail, when you are requiring more resources that those available. So you have to handle that case.
顺便说一句,您可以考虑使用 Boehm的保守垃圾收集器,并使用 GC_malloc
而不是 malloc
,并且不关心它的失败和 free
-ing.(我认为Boehm的GC将在内存不足时中止程序.)
BTW, you could consider using Boehm's conservative garbage collector and use GC_malloc
instead of malloc
and not caring about its failure and about free
-ing. (I think that Boehm's GC would abort the program when not enough memory).
这篇关于malloc在do while块中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!