[comp.lang.c] casting void pointers

hurwitz@enuxha.eas.asu.edu (Roger A. Hurwitz) (04/21/91)

Appendix A, section 6.8, of K&R 2d, states in part,

	"Unlike the pointer-to-pointer conversions discussed in [section]
	A6.6, which generally require an explicit cast, pointers may 
	be assigned to and from	pointers of type *void, and may 
	be compared with them."
	
Does this mean that the explicit cast that one always sees with
malloc() is unnecessary since malloc() returns a void pointer?
For example, why not:

	fooptr = malloc(sizeof(struct foo));
	
instead of:

	fooptr = (struct foo *) malloc(sizeof(struct foo));
	
Even K&R 2d states that an explicit cast should be used with malloc(),
in another part of the book (p. 142), but I am having trouble reconciling
that with the above language.

berg@marvin.e17.physik.tu-muenchen.de (Stephen R. van den Berg) (04/23/91)

Roger A. Hurwitz writes:
>Even K&R 2d states that an explicit cast should be used with malloc(),
>in another part of the book (p. 142), but I am having trouble reconciling
>that with the above language.

malloc does not need the cast, any compiler complaining about that is
braindamaged (or not ANSI compliant :-)
--
Sincerely,                 berg@marvin.e17.physik.tu-muenchen.de
           Stephen R. van den Berg.
"I code it in 5 min, optimize it in 90 min, because it's so well optimized:
it runs in only 5 min.  Actually, most of the time I optimize programs."

jrbd@craycos.com (James Davies) (04/23/91)

In article <4256@rwthinf.UUCP> berg@marvin.e17.physik.tu-muenchen.de (Stephen R. van den Berg) writes:
>Roger A. Hurwitz writes:
>>Even K&R 2d states that an explicit cast should be used with malloc(),
>>in another part of the book (p. 142), but I am having trouble reconciling
>>that with the above language.
>
>malloc does not need the cast, any compiler complaining about that is
>braindamaged (or not ANSI compliant :-)

In fact, the cast can actually be damaging.  If you forget to declare
malloc on a 16-bit-int machine like a PC, but then cast the returned value,
most compilers will assume you know what you're doing and quietly strip off
the high 16 bits of your 32-bit pointer.  (I once spent two days finding
a bug like this...)