Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
like image 741
bodacydo Avatar asked Jul 01 '10 22:07

bodacydo


People also ask

How many bytes are in malloc sizeof char * 10?

malloc(10) allocates 10 bytes, which is enough space for 10 chars.

How to allocate memory dynamically in c for char pointer?

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) );

What is sizeof in malloc?

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.


2 Answers

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.

like image 180
Jerry Coffin Avatar answered Sep 19 '22 17:09

Jerry Coffin


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

like image 35
AnT Avatar answered Sep 19 '22 17:09

AnT