Is this “Type of punishment” well defined?

I was wondering if it distinguishes from and the pointer to incomplete undefined behavior?

struct _obj; typedef _obj obj; typedef struct{ int val; } obj_int; void print_stuff(obj* o){ printf("%d\n", ((*obj_int)(o)) -> val); } 
+4
source share
2 answers

Usually.

Standard 6.3.2.3/7:

A pointer to an object or partial type can be converted to a pointer to another object or partial type. If the resulting pointer is not correctly aligned to type, the behavior is undefined. Otherwise, the opposite result is compared with the original pointer. When a pointer to an object is converted to a pointer to a character type, the result points to the least significant address byte of the object. Successive increments of the result, up to the size of the object, indicate pointers to the remaining bytes of the object.

So, if o points to any structure object whose first member is int , you're fine. If it points to the beginning of memory retrieved from malloc where the int representation is written, you're fine. But if it points to char[sizeof(int)] or something like that, you might have alignment problems.

+6
source

You have not provided enough information to answer your question. If you drop obj_int* into obj* and then pass it to print_stuff , then your code is legal according to the C standard, because you are allowed to point to a pointer to another type of pointer and vice versa. However, if the print_stuff argument was received in any other way, then you have undefined behavior.

+1
source

Source: https://habr.com/ru/post/1498877/


All Articles