问题描述
这是我在 OS X Yosemite
int main(int argc, char *argv[]){
while (1) {
srand(time(NULL));
int r = rand();
printf("Allocating\n");
int *pi = malloc(5000000 * sizeof(int));
if(pi==NULL){
printf("Hello");
}
memset(pi, r, 5000000 * sizeof(int));
}
}
因此该程序最终停止运行,控制台中的最后几行是:
So this program eventually stops running, last lines in Console I see being:
分配
分配
被杀:9
Korays-MacBook-Pro:hello2 koraytugay $
Korays-MacBook-Pro:hello2 koraytugay$
如果在这种情况下malloc不返回NULL,它将何时执行?我的理解是这里发生了内存分配问题,但是为什么不打印"Hello"?
If malloc does not return NULL in this situation, when will it do? My understanding is a memory allocation problem happens here, but why "Hello" is not printed?
推荐答案
如果您的内存需求超出了可用内存,Linux将终止该程序,从而使malloc从不返回NULL.
Linux will kill the program if your memory requirement exceeds available memory making malloc never return NULL.
您可以使用echo 2>/proc/sys/vm/overcommit_memory关闭此功能.
You can turn this feature off using echo 2 > /proc/sys/vm/overcommit_memory.
这篇关于为什么我在此程序的控制台中从未看到Hello文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!