I was doing some C coding and after reading some C code I\'ve noticed that there are code snippets like
char *foo = (char *)malloc(sizeof(char) * someDynamicAmo
Citing C99 standard, section 6.5.3.4 The sizeof
operator:
When applied to an operand that has type char, unsigned char, or signed char, (or a qualified version thereof) the result is 1. When applied to an operand that has array type, the result is the total number of bytes in the array. When applied to an operand that has structure or union type, the result is the total number of bytes in such an object, including internal and trailing padding.
That is, sizeof char == 1
by the standard, not by the implementation. Therefore it is absolutely correct to omit sizeof(char)
when calling malloc()
for chars and in similar cases. IMHO, it is highly improbable that future C standard will allow implementation-specific size of char
, because too much code already depends on it to be 1 and backward compatibility is very important in C.
Therefore, the question is only about style, not correctness and here I support AProgrammer's answer.