为什么的malloc()或新从未返回NULL? [英] Why does malloc() or new never return NULL?

查看:159
本文介绍了为什么的malloc()或新从未返回NULL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写这需要大量的内存用于高速缓存目的的应用href=\"http://stackoverflow.com/questions/16641932/dynamical-memory-allocation-making-use-of-unused-memory\">here.现在我玩弄一些的malloc /新建筑要弄清楚我怎么能意识到这一点。我做了一个奇怪的观察:

I'm writing an application which needs a lot of memory for caching purposes as I described he here. Now I'm playing around with some malloc / new constructions to figure out how I could realise it. I made a strange observation:

#include <stdio.h>
#include <stdlib.h>

int main(void) {
  while(1) {
    char *foo = (char*)malloc(1024);// new char[1024];
    if(foo == NULL) { 
      printf("Couldn't alloc\n");
      fflush(stdout);
      return 0;
    }
  }
  return 0;
}

为什么说printf的永远无法实现?如果我的系统运行的内存,malloc的据说是返回NULL,因为它是这里解释。但是,我总是收到SIGKILL(我使用Linux ...)。

Why does that printf never be reached? If my system runs out of memory, malloc is said to return NULL, as it is explained here. But I always receive SIGKILL (I'm using linux...).

推荐答案

Linux的,默认情况下,通常采用一种机会主义的内存分配方案,这意味着内核会给你不会被分配到第一次使用一个有效的地址。

Linux, by default, usually uses an opportunistic memory allocation scheme, meaning the kernel will give you a valid address that won't be allocated until first use.

请参阅:

  • SIGKILL while allocating memory
  • C Program on Linux to exhaust memory

根据这些反应可以关闭此功能使用回声2 - ;的/ proc / SYS / VM / overcommit_memory

According to those responses you can turn this feature off using echo 2 > /proc/sys/vm/overcommit_memory.

据我所知,这是你不会必然使用所有你分配内存的前提下进行。我不能说,我个人曾经分配,我不碰至少一次的空间,所以我很好奇,想知道这如何影响现实生活中的表现...

From what I can tell, this is done under the assumption that you wont necessarily use all the memory that you allocate. I can't say that I personally ever allocate space that I don't touch at least once, so I'd be curious to know how this affects real life performance...

关于SIGKILL失败,每一次你调用malloc仍然分配每次调用一些内存。最终,你将有可能填补malloc的开销,你的记忆,因而唤起了内存抑制功能的愤怒。这是否是单独的问题,或者可能是过量使用的政策仍然分配请求的空间的某一部分是一个很好的问题。

Regarding the SIGKILL failure, every malloc you call is still allocating some memory for each call. Eventually you will likely fill your memory with malloc overhead and thus evoke the fury of the out of memory kill feature. Whether this alone is the issue or if perhaps the overcommit policy still allocates some fraction of the requested space is a good question.

这篇关于为什么的malloc()或新从未返回NULL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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