I see that people often write C code such as:
char *ptr = malloc(sizeof(char)*256);
Is that really necessary? The standard says that sizeof(char)==1
by definition, so doesn't it make sense just to write:
char *ptr = malloc(256);
malloc(10) allocates 10 bytes, which is enough space for 10 chars.
In C, the RAM should use the following code to allocate the two-dimensional array: *contents = (char**) malloc(sizeof(char*) * numRows); **contents = (char*) malloc(sizeof(char) * numColumns * numRows); for(i = 0; i < numRows; i++) (*contents)[i] = ( (**contents) + (i * numColumns) );
The malloc line allocates a block of memory of the size specified -- in this case, sizeof(int) bytes (4 bytes). The sizeof command in C returns the size, in bytes, of any type. The code could just as easily have said malloc(4), since sizeof(int) equals 4 bytes on most machines.
Yes, C defines sizeof(char)
to be 1, always (and C++ does as well).
Nonetheless, as a general rule, I'd advise something like:
char *ptr = malloc(256 * sizeof(*ptr));
This way, when your boss says something like: "Oh, BTW we just got an order from China so we need to handle all three Chinese alphabets ASAP", you can change it to:
wchar_t *ptr // ...
and the rest can stay the same. Given that you're going to have about 10 million headaches trying to handle i18n even halfway reasonably, eliminating even a few is worthwhile. That, of course, assumes the usual case that your char
s are really intended to hold characters -- if it's just a raw buffer of some sort, and you really want 256 bytes of storage, regardless of how many (of few) characters that may be, you should probably stick with the malloc(256)
and be done with it.
The issue should not even exist. You should adopt a more elegant idiom of writing your malloc
's as
ptr = malloc(N * sizeof *ptr)
i.e. avoid mentioning the type name as much as possible. Type names are for declarations, not for statements.
That way your malloc
s will always be type-independent and will look consistent. The fact that the multiplication by 1 is superfluous will be less obvious (since some people find multiplication by sizeof(char)
annoying).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With