Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it ok to cast to an undeclared struct pointer in C?

Tags:

c

Why does this code compile? struct test is not even forward declared.

int main(){

 *(int*)((struct test*) 0x1234) = 0x0;

 return 0;
}
like image 253
Dan Avatar asked Dec 11 '25 13:12

Dan


2 Answers

The appearance of struct test* is an implicit declaration of struct test. Specifically, struct test declares the type.

Because the struct type is declared a pointer to that type is valid. Even though the struct type was not fully defined, the representation of the pointer type is known since a pointer to any struct type has the same representation as described in section 6.2.5p33 of the C standard:

All pointers to structure types shall have the same representation ... as each other

This means the type struct test* is a complete type, which allows the cast to happen.

like image 174
dbush Avatar answered Dec 14 '25 03:12

dbush


Because in this case the compiler does not need to know the size of the structure test, and the address is still eventually cast to the int * type.

like image 24
zenbooster Avatar answered Dec 14 '25 03:12

zenbooster



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!