1

Please consider the following code:

typedef struct {
    int base_value;
} Base;

typedef struct {
    Base base;
    int child_value;
} Child;

Base* base = get_thing();
Child* child = (Child*) base;

Is the following guaranteed to always work, or is it implementation-dependent?

printf("%d", child->base_value);

Please note I'm not going through base first (child->base.base_value), but going directly to base_value.

Aviv Cohn
  • 15,543
  • 25
  • 68
  • 131
  • 1
    Possible duplicate of [In C, does a pointer to a structure always point to its first member?](https://stackoverflow.com/questions/7312555/in-c-does-a-pointer-to-a-structure-always-point-to-its-first-member) – UnholySheep Apr 26 '19 at 22:19
  • 3
    It is guaranteed to never work. `Child` does not have a member called `base_value`. – melpomene Apr 26 '19 at 22:44
  • the type `Child` does not have a member called `base_value` so the line `printf("%d", child->base_value);` does not compile because you have casted it to type `Child`. There are other problems too. The actual object is a `Base` but since you casted it to `Child` the compiler will treat it as `Child` so you could try to access `child->base` or `child->child_value`. The actual object is type `Base` so accessing `child_value` is UB in every implementation. – Chris Rollins Apr 26 '19 at 22:44
  • It generally makes more sense to cast `Child*` to `Base*`, not the other way around. – Barmar Apr 26 '19 at 23:06
  • An exception is when calling a "Factory" method. – Barmar Apr 26 '19 at 23:07
  • Since you've not shown how `get_thing()` is written, it is not possible to know whether it allocates enough space for a `Child` or whether it only allocates enough space for a `Base` (or, indeed, whether it allocates anything, or returns a valid pointer to anything). This is why an MCVE ([MCVE]) is important. Missing details often matter. – Jonathan Leffler Apr 27 '19 at 05:20

0 Answers0