In a bunch of programs I came across regarding dynamic memory allocation I always find the same piace of code when it was need to allocate dynamic memory:
int *pointer = (int *)malloc(sizeof(int));
if(pointer == NULL)
exit(1); // or return 1
// else the program keep running
I was wondering why it's not used, or at least I've never seen it, something like that:
int *pointer
while((pointer = (int *)malloc(sizeof(int)) == NULL);
I though about it and the only thing I came up with is that if you can't allocate new memory is because there is no more left on the heap so the 2nd example would turn into an infinite-loop. Is that right? Because if the memory allocation fails for some other reasons (I don't really know which) than putting the allocation inside a loop would probably solve the problem.
Am I missing something? Which one of the "style" is preferred?