Eric Sosman said:
Almost anyone.
Another current thread has degenerated into a useless
squabble about whether the (NODE*) cast is or is not a good
idea. Here is an instance where it is demonstrably a *bad*
idea, because it *did* hide an error that would otherwise
have been caught. Try removing the cast, and see what your
compiler tells you. (Even with the cast in place, some
compilers will warn about the error if their diagnostic
sensitivity is "dialed up" a bit. Check your compiler's
documentation to see if there's a way you can do so, because
warnings can be helpful in many other circumstances, too.)
yep, in my case it depends on the code, as in, whether I might consider
compiling it as C++ rather than as C...
in a few rare cases, I have had code which had started out as C but was then
later transitioned to C++, and in general try to write code which is fairly
neutral between them.
so, alas, casting malloc is one of those things:
some people like it, others despise it;
it is much like the whole "()" vs "(void)" issue...
There's also the little matter that malloc() might fail
to find enough memory for your request, in which case it will
return NULL. If you then try things like `head->name=...'
when `head' is NULL, there will be trouble. True, in a toy
program like this it is overwhelmingly likely that malloc()
will find enough memory and return a non-NULL, but *do* *not*
get into the habit of forgetting to inspect what you get!
assuming this much works as expected in a modern OS...
it is also very possible that:
the malloc does not fail to allocate memory until all the address space is
used (say 2GB or 3GB for a 32-bit process);
either the OS kills the process, or something crashes within the C library,
before this point.
yeah, I actually did have a program at one point which exhausted the entire
address space via little more than 'strdup' and allocating 'node'
structures. granted, it was also implementing an HMM, I think order-5 (or
similar) and for a fairly big chunk of text...
some time later, in 64 bit land, I allocated enough memory that, although
things never returned NULL, the OS ground to a halt and I was half afraid
that the OS would crash instead (resulting mostly from allocating around 5GB
of memory on a computer with 2GB of RAM...).
so, yes, the powers of virtual memory...
the C library may not know anymore when is a reasonable limit, or when
memory is exhausted, it may well just keep going until something more
fundamental breaks (such as the amazing BSOD...).