Quote:
>* Casting its return value can mask a failure to #include
><stdlib.h>, which leads to undefined behavior.
[This is for the benefit of the OP, not an attempt to correct Ben]
More specifically, the absence of a correct declaration for malloc
causes this problem. When the compiler sees the call to malloc (a
function it has never heard of before) it is required to assume that
the return type of this new function is int. When malloc returns, the
calling code attempts to fetch an int value from wherever it expects
such a return value to be. Since there was no int return value (only a
void *), and there's no guarantee that void pointers are returned the
same way as ints, it may fetch a completely incorrect value. This
garbage value is then converted to a pointer (thanks to the
superfluous cast) and stored into the pointer variable on the
left-hand side of the assignment. Obviously, this is a big problem.
This is just an example of how it might fail. The bottom line is that
having the wrong return type for malloc results in undefined behavior
- anything could happen. It could work today and format your hard
drive tomorrow.
Without the cast, the compiler has to complain about an apparent
attempt to assign an int to a pointer. This gives the programmer a
chance to fix the problem by providing a correct declaration for
malloc (most likely by #includeing stdlib.h).
-Kevin