(void *) ? /* again */

Conor P. Cahill cpcahil at virtech.uucp
Mon Jan 22 21:35:43 AEST 1990


In article <21771 at unix.cis.pitt.edu>, yahoo at unix.cis.pitt.edu (Kenneth L Moore) writes:
> 
> Have you tried to coerce the type with 
>     
>        plong = (long *) malloc(sizeof(long)); 
> 
> and no declaration of malloc? This way you can use malloc for several
> different types of pointers in the same program.

Never use malloc() without declaring it as returning a pointer.  The 
cast you list will get rid of the warning from most compilers and
will not have any detrimental effect on the program.  However, 
removing the declaration for the malloc() can have a very bad effect
on the program on some systems. 

For example, an old 68000 compiler used to use register d0 (or maybe it
was d1) to return data values from a function that was declared as
returning an int and used register a0 to return pointer values.  Since
malloc() in the library is declared to return a pointer the malloc() 
function placed the return value in register a0.  

Now if you told the compiler that malloc returned an int (by not declaring it
as returning a pointer) the compiler would assume that the return value
was in register d0 and would assigne what was in d0 to your variable
even though the return value was actually in a0.

If you used a cast to quiet the warning what you would see is that the 
compiler moved the bogus value that was in d0 to register a0 before assigning
it to your variable, so you still ended up with bogus data.

The moral of the story is to always declare the function return type using
the type that was used when the function was coded and, if necessary, cast
this type to the type you need.

-- 
+-----------------------------------------------------------------------+
| Conor P. Cahill     uunet!virtech!cpcahil      	703-430-9247	!
| Virtual Technologies Inc.,    P. O. Box 876,   Sterling, VA 22170     |
+-----------------------------------------------------------------------+



More information about the Comp.lang.c mailing list