In C are malloc(256) and malloc(sizeof(char)*256) equivalent?

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 chars 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 mallocs 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).


They're equivalent, but it's good to remain consistent. It also makes it more explicit, so it's obvious what you mean. If the type ever changes, it's easier to find out what code needs to be updated.