In the following code, will freeing Dairy free Yogurt as well?
Both point to the same address as far as I know.
Also, is this style of coding a bad practice? Say if I only kept pointers to the Dairy and indirectly freed the Yogurt and Cheese as well?
#include <stdlib.h>
typedef struct {
int calcium;
int protein;
} Dairy;
typedef struct {
Dairy dairy;
int sugar;
int color;
} Yogurt;
int main () {
Yogurt* yogurt = malloc(sizeof(Yogurt));
Dairy* dairy = &yogurt->dairy;
free(dairy); // Will this free yogurt?
}
Yes the behavior is well-defined.
As per the C Standard You need to pass the exact same address to deallocation function
freeas was returned by anmallocor other allocation functions.Reference:
So, In this case the behavior is guaranteed to be well defined if and only if pointer to the structure is same as pointer to it’s first member.
And that is guaranteed by the standard in:
6.7.2.1 Structure and union specifiers
§15