如果malloc分配失败,我们应该再试一次吗?
在这样的事情:
char* mystrdup(const char *s)
{
char *ab = NULL;
while(ab == NULL) {
ab=(char*)malloc(strlen(s)+1);
}
strcpy(ab, s);
return ab;
}
Run Code Online (Sandbox Code Playgroud)
while循环对检查内存分配有效吗?
阅读Martin Sustrick撰写的有关在C++中防止"未定义行为"的问题的博客,特别是由于内存耗尽而导致malloc()失败的问题,我被提醒了很多次,我很沮丧地知道是什么在这种情况下做.
对于虚拟系统来说,这种情况很少见,但是在嵌入式平台上,或者在击中虚拟系统时伴随着性能下降等同于失败的情况,正如Martin对ZeroMQ的情况一样,我决定找到一个可行的解决方案,并且做到了.
我想向StackOverflow的读者询问他们是否尝试过这种方法,以及他们使用它的经验.
解决方案是在程序开始时调用malloc()从堆中分配一块备用内存,然后使用该备用内存池来避免内存耗尽.这个想法是为了防止投降有利于有序撤退(我正在阅读Kesselring昨晚对意大利的辩护的说法),其中错误信息和IP套接字等工作时间足够长(希望)至少告诉用户发生了什么.
#define SPARE_MEM_SIZE (1<<20) // reserve a megabyte
static void *gSpareMem;
// ------------------------------------------------------------------------------------------------
void *tenacious_malloc(int requested_allocation_size) {
static int remaining_spare_size = 0; // SPARE_MEM_SIZE;
char err_msg[512];
void *rtn = NULL;
// attempt to re-establish the full size of spare memory, if it needs it
if (SPARE_MEM_SIZE != remaining_spare_size) {
if(NULL != (gSpareMem = realloc(gSpareMem, SPARE_MEM_SIZE))) {
remaining_spare_size = SPARE_MEM_SIZE;
// "touch" the memory so O/S will allocate physical …Run Code Online (Sandbox Code Playgroud)