Yes, it's necessary. Think of malloc
as giving you a box. In this box you can do all kinds of magical stuff. All you need to tell malloc
how big the box needs to be.
n * sizeof(char)
is the size of the box (n x the size of the char type dictated by the compiler -- I think it's always 1
for variations of char
though, but you should never count on these things, especially if developing for embedded systems).
Basically, you cannot do something like buf = malloc()
as it wouldn't even compile.
Edit: To answer your second question, try running and compiling this:
#include <iostream>
int main()
{
std::cout << sizeof(double) << std::endl;
std::cout << sizeof(char);
}
You'll see that sizeof(double)
is, or should be, 8
, and sizeof(char)
is, or should be, 1
. So in your case it would make the box have a "size" of 1 x n
bytes in the case of the char
or 8 x n
bytes in the case of the double
.
Usually, it's not smart to allocate a ton of memory if you don't use it.