Why I never see the Hello text in Console in this

2019-05-19 00:11发布

问题:

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).