Is it bad practice to allocate memory like this?:
FOO *foo;
while (!(foo = malloc(sizeof(FOO)))) ;
Is it bad practice to allocate memory like this?:
FOO *foo;
while (!(foo = malloc(sizeof(FOO)))) ;
I don't know about bad practice, but it's uncommon. malloc()
failures are usually indicative of major system problems that your program is unlikely to be able to recover from. If your system is different, your example may very well be practical.
NB - this answer assumes that sizeof(FOO)
is "reasonable" and that your malloc()
doesn't just refuse because you're asking for too much memory.
That doesn't "guarantee" a result from malloc()
. If malloc returns NULL
there's probably a reason for it (out of memory for example). And you might throw yourself into an infinite loop.
Furthermore, if you're running this on a Linux platform:
By default, Linux follows an optimistic memory allocation strategy. This means that when malloc() returns non-NULL there is no guarantee that the memory really is available.
That means that lets say calling malloc over and over again did happen to return something non-NULL, due to Linux's "optimistic" strategy, a non-NULL still doesn't guarantee you got anything that will work.
I think this code is setting you up for a debugging nightmare.