I just wonder what's happen when free() called about member of struct tonight. Let see below simple code in c.
typedef struct {
int c[5];
int a[10];
int *b;
}stma;
int main() {
stma *he = (stma*)malloc(sizeof(stma));
int *ac = he->a;
free(ac); //This point is crash.
return 0;
}
The free make crash. But next code is work well.
typedef struct {
int c[5];
int a[10];
int *b;
}stma;
int main() {
stma *he = (stma*)malloc(sizeof(stma));
int *ac = he->c; //This point is changed.
free(ac); //Work well.
return 0;
}
Of course, I could think second will work well and first is not correct code too.
What I wonder is what is happen during first execution. free() free 'a' variable, the middle of struct, not address of struct.
he->a is not malloced, dynamically assigned and couldn't be free. In this case, he->c memory address is 00D2Ad50 and he->a is 00D2AD64. The struct variable will be placed in heap by malloc(). he->c have same address of 'he'. And he->c + 4*5 is he->a. he->a is also in heap? Then, what happen on free(he->a)?