Mail Archives: djgpp/1996/11/12/00:01:42
George Foot wrote:
> If you forget to #incldue <stdlib.h>, the compiler will not warn you when
> you implicitly define the function int malloc (...), and will then put a
> cast in from integer result to (xxx *). I believe this works on gcc, but
> whether it is portable is another matter. The point is, you are
> suppressing an important warning.
Not including stdlib.h when using malloc/free is generally a bad idea on
most C compilers, DJGPP or otherwise -- since malloc/free are such
fundamental functions, generally their existence is assumed even though
your not including them may not get the right library linked in. When you
get weird malloc/free warnings/errors, or when malloc starts misbehaving
when you're calling it in an innocent manner, this is generally the cause.
(I've had this happen to me on at least half a dozen compilers.)
> If you leave out the cast, it will complain about an implicit cast from
> integer to pointer, which indicates the problem.
Yes. Any cast except a simple promotion (e.g., from char to int) or from a
pointer to void * (which is always implicitly legal) should generate a
warning or error. Casting from a non-pointer type to a pointer type
generally indicates a bigger problem (i.e., you're doing something you
really shouldn't be).
> If you #include the header, it works both ways with no warnings.
It is an ANSI C violation to implicitly convert a void * (which is what
malloc returns) to any other kind of pointer. Your compiler, if it is good
enough, should not let you do this, or at the very least give you a very
prominent warning. The cast makes it ANSI C.
> Conclusion: In C, the explicit cast is a bad idea because it can mask a
> warning of a potentially serious error. In C++, the cast is necessary to
> remove an ANSI warning.
It is not ANSI C to have an implicit conversion from void * to some other
pointer type. You should always include the cast.
--
Erik Max Francis | max AT alcyone DOT com
Alcyone Systems | http://www.alcyone.com/max/
San Jose, California | 37 20 07 N 121 53 38 W
&tSftDotIotE | R^4: the 4th R is respect
"But since when can wounded eyes see | If we weren't who we were"
- Raw text -