Re: Type-casting void pointers?
Keith Thompson <kst-u@mib.org> writes:[color=blue]
> Chris Croughton <chris@keristor .net> writes:
> [...][color=green]
>> In particular, I've never come across any case in professional
>> programming where casting malloc() (or other void pointer) actually
>> masked a failure to declare it or include the relevant header file,
>> whereas I have come across cases where:
>>
>> pointer = (my_type*) malloc(sizeof(m y_type));
>>
>> correctly pointed out that the type of the pointer was not the same as
>> expected, whereas just assigning the void pointer wouldn't have created
>> any diagnostic at all.[/color]
>
> Which is why the recommended idiom is
>
> pointer = malloc(sizeof *pointer);[/color]
Following up to myself ...
On the other hand, the cast could conceivably reveal the error that
"pointer" should be of type my_type, but is actually of type
some_other_type . This assumes that the correct type is more obvious
in the context of the malloc() call than at the point of declaration.
I still think it's more likely to mask an error than to reveal one.
--
Keith Thompson (The_Other_Keit h) kst-u@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Keith Thompson <kst-u@mib.org> writes:[color=blue]
> Chris Croughton <chris@keristor .net> writes:
> [...][color=green]
>> In particular, I've never come across any case in professional
>> programming where casting malloc() (or other void pointer) actually
>> masked a failure to declare it or include the relevant header file,
>> whereas I have come across cases where:
>>
>> pointer = (my_type*) malloc(sizeof(m y_type));
>>
>> correctly pointed out that the type of the pointer was not the same as
>> expected, whereas just assigning the void pointer wouldn't have created
>> any diagnostic at all.[/color]
>
> Which is why the recommended idiom is
>
> pointer = malloc(sizeof *pointer);[/color]
Following up to myself ...
On the other hand, the cast could conceivably reveal the error that
"pointer" should be of type my_type, but is actually of type
some_other_type . This assumes that the correct type is more obvious
in the context of the malloc() call than at the point of declaration.
I still think it's more likely to mask an error than to reveal one.
--
Keith Thompson (The_Other_Keit h) kst-u@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Comment