views:

781

answers:

4

I wanted to ask about the following case:

char *temp;
temp=malloc(10);

Since the return type of malloc is void, will the pointer returned by the malloc be implicitly cast to char type before being assigned to temp? What does the standard say in this regard?

If our pointer variable is some struct type for ex.

struct node *temp;
temp=(struct node *)malloc(sizeof(struct node));

If we allocate memory to temp without casting it to struct node type, will it be implicitly cast to struct node type or is it necessary to explicitly cast it to struct node type?

+4  A: 

C implicitly casts from and to void*, so the cast will be done automatically. In C++ only conversion to void* would be done implicitly, for the other direction an explicit cast is required.

sth
Note C++ does support conversion to a void * without a cast.
anon
+5  A: 

A void pointer in C can be assigned to any pointer without an explicit cast.

tekBlues
I don't think it applies to function pointers.
Bastien Léonard
C leaves it undefined whether you can cast function pointers to non-function pointers or back. C++ explicitly forbids it, and C++1x conditionally supports it
Johannes Schaub - litb
And POSIX (2008 at least) requires that function pointers are the same size as data pointers, where the C standard leaves that undefined.
Jonathan Leffler
+1  A: 

In C++ you must explicitly cast, but this is really just the language telling you off for doing it.
In c there isn't really any need to cast, memory is just memory - I will have to do a search to see if the latest C standard requires it.

Martin Beckett
The C99 standard does not require the cast.
Jonathan Leffler
+6  A: 

If you like the "don't repeat yourself" mindset, it should be appealing that you don't need to repeat the type name from the declaration of the variable, in the malloc() call. Because, as folks have pointed out, you don't: pointers convert to and from void * without loss, with the exception of function pointers.

Also, on that note, you don't need to repeat yourself with the use of sizeof either. Your second example, when allocating a structure, can be written like this:

struct node *temp;
temp = malloc(sizeof *temp);

Which in my not so humble opinion is the best way. Avoiding repeating yourself cuts down on the number of things you write, which in turn cuts down on the risk that any of those things are wrong. Note the asterisk in the sizeof argument, this means "the size of the object pointed to by this pointer", which is of course the same as "the size of the type struct node" but without repeating the type name.

Sure, you do repeat something, i.e. the variable name itself, but that is often a simpler expression and easier to get right, and also can be easier for the compiler to spot an error in.

unwind
+1 sizeof *temp
You can call me Chuck