José de Paula said:
Is it a given that sizeof(char) always yields 1, no matter the
implementation? I ask because I saw some critics against
char * ptr = malloc (sizeof(char) * NUM);
in favour of simply
char * ptr = malloc (NUM);
sizeof (char) is absolutely always equal to 1.
Multiplying by sizeof (char) is redundant. But sometimes it is the right
thing to write code that is redundant if it makes more clear what you
mean.
"char" is often used as an integer type in its own right, in places
where you would use "short short int" if such a type existed, and then
multiplying by sizeof (char) would be the right thing to do. If you want
to allocate n elements of type X then you call malloc (n * sizeof (X)).
For example
// I need three arrays of hundred elements to store data
char* array1 = malloc (100 * sizeof (char));
short* array2 = malloc (100 * sizeof (short));
double* array3 = malloc (100 * sizeof (double));
But quite often "char" is used just as the unit of storage; you
calculate a number of bytes and then you allocate that many bytes.
Multiplying (number of bytes) by (sizeof (char)) seems to indicate that
the author doesn't quite understand what is going on.