5

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.

0

1 Answer 1

4

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.

6
  • 1
    Yes, exactly. sizeof *pfds is interpreted as "the size of whatever thing pfds points to." And this is preferable because the code will still work even if pfds is redefined to point to something else. (In fact, code as written in your second example ... and rest assured that there's plenty of it out there ... might, after just such a change, be: "a nas-s-s-s-s-sty bug!"* Commented Mar 26, 2020 at 21:01
  • I'm sorry for the time I wasted. I'm not this stupid all the time.
    – asds_asds
    Commented Mar 26, 2020 at 21:01
  • @MikeRobinson I did learn a way to write better and safer code and that counts. The community is really helpful. Stay safe and stay home.
    – asds_asds
    Commented Mar 26, 2020 at 21:08
  • 1
    @asds_asds I agree with the answer, but if I can provide an unrequested piece of advice I say: use parenthesis around sizeof argument. Parenthesis are free! :) (I know there's people believing that it is more readable, but I don't agree. And every time I see a sizeof argument not enclosed by parenthesis a cute kitten dies :) ) Commented Mar 26, 2020 at 21:26
  • 2
    @RobertoCaboni, FWIW I feel the exact opposite. sizeof is an operator. The extra parentheses make me sad. Not as bad as return(x); makes me feel, but still sad.
    – Carl Norum
    Commented Mar 26, 2020 at 23:07

Not the answer you're looking for? Browse other questions tagged or ask your own question.