tags:

views:

91

answers:

3

Hi recently I saw a lot of code on online(also on SO;) like:

   char *p = malloc( sizeof(char) * ( len + 1 ) );

Why sizeof(char) ? It's not necessary, isn't it? Or Is it just a matter of style? What advantages does it have?

+4  A: 

Yes, it's a matter of style, because you'd expect sizeof(char) to always be one.

On the other hand, it's very much an idiom to use sizeof(foo) when doing a malloc, and most importantly it makes the code self documenting.

Also better for maintenance, perhaps. If you were switching from char to wchar, you'd switch to

wchar *p = malloc( sizeof(wchar) * ( len + 1 ) );

without much thought. Whereas converting the statement char *p = malloc( len + 1 ); would require more thought. It's all about reducing mental overhead.

brainjam
Then why not use type *p = malloc( sizeof(*type) * (len+1) );;)
Nyan
Oh I meant sizeof(*p)
Nyan
@Nyan: Sure, that works too. I've never seen this before, but if I were still a working C programmer I would consider adopting your suggestion as an idiom .. although the `len +1` part would only be for string-like objects.
brainjam
Not only would you expect it to be 1 it's defined to be so. One of the very few items whose size is explicitly defined.
JaredPar
+1  A: 

It serves to self-document the operation. The language defines a char to be exactly one byte. It doesn't specify how many bits are in that byte as some machines have 8, 12, 16, 19, or 30 bit minimum addressable units (or more). But a char is always one byte.

Amardeep
+1  A: 

The specification dictates that chars are 1-byte, so it is strictly optional. I personally always include the sizeof for consistency purposes, but it doesn't matter

Michael Mrozek