6

I was looking at a port of libusb today for android and I noticed this line of code:

struct usbi_pollfd *ipollfd = malloc(sizeof(*ipollfd));

It seems that ipollfd is being allocated based on the size of itself which has not been completely allocated yet. My first thought would be that the behavior of this is undefined. Is that the case?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Dom
  • 1,687
  • 6
  • 27
  • 37

1 Answers1

7

It's fine and well-defined behaviour.

sizeof gets evaluated at compile-time, and unless the operand is VLA, the operand is not evaluated. (So, no invalid-pointer dererefence, as it might look like)

To put it in other words, sizeof only needs to know the type of the operand (which is already defined).

Quoting C11, chapter ยง6.5.3.4

[....] If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261