Alex Rivera | Logout

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

Asked 2010-07-01T22:10:32.887
14

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

2 Answers

6

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

answered 2010-07-01T22:21:04.767
4

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.

answered 2010-07-01T22:13:12.837

Your Answer