Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it defined behavior to allocate memory using the variable being declared? [duplicate]

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?

like image 951
Dom Avatar asked May 11 '16 17:05

Dom


1 Answers

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.

like image 135
Sourav Ghosh Avatar answered Nov 04 '22 03:11

Sourav Ghosh