casts

NEP.FOUTS at Ames-Vmsb.ARPA NEP.FOUTS at Ames-Vmsb.ARPA
Fri Mar 23 19:21:00 AEST 1984


The C program d.c:
              
( 1)		char * malloc( );
( 2)		struct x {
( 3)			int a; 
( 4)		};      
( 5)		main(){ 
( 6)			struct x *p;
( 7)			p = (struct x *)malloc((unsigned) sizeof (struct x));
( 8)			free((char *)p);
( 9)		}       
              
(line numbers appended for reference.) run through lint with the command:
              
		lint -c d.c 
              
Gives the output:
              
		d.c:        
		d.c(7): warning: illegal pointer combination
		d.c(8): warning: illegal pointer combination
              
The problem apparently being that p is a pointer to a structure of type x,
while malloc(3) returns a pointer to an array of characters.  According to
[1], this construction is ". . . the safest course . . ."  If this is so,
why does lint generate the "illegal pointer combination" messages, and
wht is a better way (short of writing memory allocation routines for each
structure in the program) to handle this problem?
              
I realize that using the '-c' option on lint is supposed to complain about
casts, as described in [2], but I guess the real question is how to define
a mechanism for "portable casts" which allows those casts which can be moved
from one place to another to do so.
              
Or, perhaps, I don't understand the use of casts.  It appears to me that a
cast is supposed to be the "safe" way to do data type conversion.  It also
appears that pointers are a type where it should be possible for the system
to do this conversion.

By the way, is there a C implementation in which this particular use of
malloc(3) will fail?
              

-----         
[1] The C Programming Language; Kernighan, Brian W. and Ritchie, Dennis M.,
    Prentice-Hall, Inc., Englewood, Cliffs, New Jersey; Chapter 6, page 134
              
[2] Lint, a C Program Checker; (in Unix Programmer's Manual, Seventh Edition,
    Volume 2a, January, 1979); S. C. Johnson, Bell Laboratories,
    Murray Hill, New Jersey, page 4
------



More information about the Comp.unix.wizards mailing list