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
Writing sizeof(char)
is not "future-proofing" your code against possible changes in the standard. It's usually a sign of complete misunderstanding of what sizeof
means and the whole fundamental model of memory objects in C - what's referred to as Representation of Types in the language of the C standard. The only reason a sizeof
operator even exists or makes sense is because C specifies objects to have a "representation" in memory in terms of a smallest possible unit that is unsigned char
. If not for this, storage would be a lot more abstract and there would be no use of sizeof
and the related pointer arithmetic.
sizeof
is defined in units of char
, i.e. sizeof(T)==N
means type T
occupies N
char
s. In light of this, sizeof(char)
is completely silly; it's attempting to measure how many char
s a char
occupies.
Compare:
float*baz = malloc(sizeof(float) * someDynamicAmount);
int *bar = malloc(sizeof(int) * someDynamicAmount);
char *foo = malloc(sizeof(char) * someDynamicAmount);
Vs:
float*baz = malloc(sizeof(float) * someDynamicAmount);
int *bar = malloc(sizeof(int) * someDynamicAmount);
char *foo = malloc(someDynamicAmount);
I like the first version. Do you prefer the second?
The standard is deliberately vague about the sizes of common types. [Wikipedia]
While it is unlikely that the size of a char
won't change, but the size of short
has changed. The idiomatic way is:
type_t *foo = malloc(sizeof(type_t) * someDynamicAmount);
for any type (common or complex) type_t or
type_t *foo = malloc(sizeof(*foo) * someDynamicAmount);
So that you can decide to make changes to the type of foo later on and only change it in one place.
The more Cish way would be
char* foo = malloc(someDynamicAmount * sizeof *foo);
referencing the variable and not the type so that the type isn't needed. And without casting the result of malloc (which is C++ish).
I do sizeof(char)
to make the intentions clear. If anyone ever decides he wants foo to be an int
he knows he'll need to do sizeof(int)
for it to keep on working.
or omit it and use the number
Plus it's not very good coding practice to use magic numbers.
The coding style can also be written as :-
char *foo = (char *)malloc(1 * someDynamicAmount);
But this is done so that the dynamically allocating memory can be increased according to the no of basic data type one wants. if u wanna increase 100 char it will increase 100 char. If may not have need but if we write 101 or 102 doing that would waste memory. doing the it according to the basic data type would not waste any memory space