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