Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doubt in malloc. C (Linux)

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

like image 734
Pavitar Avatar asked Dec 13 '25 18:12

Pavitar


1 Answers

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.

like image 157
linuxuser27 Avatar answered Dec 15 '25 15:12

linuxuser27



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!