Why I never see the Hello text in Console in this program?

≯℡__Kan透↙ 提交于 2020-01-02 19:27:07

问题


This is the code I have, running on 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:

Allocating

Allocating

Allocating

Killed: 9

Korays-MacBook-Pro:hello2 koraytugay$

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?


回答1:


Linux will kill the program if your memory requirement exceeds available memory making malloc never return NULL.

You can turn this feature off using echo 2 > /proc/sys/vm/overcommit_memory.




回答2:


I would suspect that printf queues "Hello" for output, then you try to memset with null pointer and process gets killed before queued "Hello" is processed. You can try flushing stdout after Hello (fflush).



来源:https://stackoverflow.com/questions/29613162/why-i-never-see-the-hello-text-in-console-in-this-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!