

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

In the following code,what is the meaning of buf = malloc(n * sizeof(char));

is n*sizeof(char) necessary,if yes.. please elaborate.

int n;

char* buf;

fstat(fd, &fs);

n = fs.st_size;

buf = malloc(n * sizeof(char));

EDIT1 And What if I write (n*sizeof(double))

share|improve this question
It's not necessary, because sizeof(char) is always 1. However, some people prefer it for uniformity; it's evaluated at compile-time, so it doesn't matter much. – Matthew Flaschen Sep 4 '10 at 4:41
It's always 1 in C99 compliant compilers, which you should always take with a grain of salt. Even most modern compilers aren't "fully" C99 compliant. – David Titarenco Sep 4 '10 at 4:50
@David, it's required since C89, if not before. – Matthew Flaschen Sep 4 '10 at 5:06
The definition of sizeof has always been in units of char. Nothing else would make any sense. A char is one char so its size is 1. – R.. May 30 '11 at 2:31
up vote 6 down vote accepted

The malloc function allocates bytes and takes as input the number of bytes you would like to allocate. The sizeof operator returns the number of bytes for a given type. In this case a char is 1 byte, but in the case of an int it is most likely 4 bytes or double is most likely 8 bytes. The expression n * sizeof(char) converts the number of char into the number of bytes that are desired.

In the case illustrated, using char, computing the number of bytes is probably not needed, but it should be done as it helps to convey your intent.

What the expression is doing is allocating the desired amount of memory needed to hold at most n number of char's and returning you a pointer, buf, to the beginning of that allocated memory.

share|improve this answer
Perhaps the OP is asking because sizeof(char) is defined to always be 1. – Ed S. Sep 4 '10 at 4:47
I thought of that, but all that it will ever cost anyone is a multiply by 1 instruction in the event they are doing char. I think conveying intent here weights out. – linuxuser27 Sep 4 '10 at 4:53
...and the compiler will optimize away the multiplication by 1. – Jonathan Leffler Sep 4 '10 at 5:25
@Jonathan Leffler - Bingo ;) Just for intent – linuxuser27 Sep 4 '10 at 5:50

The ISO standard defines a byte as the same size as a char.

You never need sizeof(char) for malloc

share|improve this answer

Your Answer


