malloc should be given size of pointer or size of memory?

Viewed 96

I was going through Beej’s Guide to Network Programming and on Page45 the following piece of code was written;

struct pollfd *pfds = malloc(sizeof *pfds * fd_size);

I was wondering if it should be

struct pollfd *pfds = malloc(sizeof(struct pollfd) * fd_size);

Since malloc returns a pointer to a memory block of the specified size.

Since *pfds is a pointer its size will be either 4 or 8 bytes, so I can't understand why its size is being considered while creating the array.

1 Answers

sizeof *pfds is the size of the structure, not the size of the pointer. Both of your examples are equivalent. I prefer the first form, since it's easier to maintain - if the type of the structure changes, you only have to fix it in one spot.

sizeof pfds would be the size of the pointer.

Related