pointers - Accessing points inside structs inside unions - C -
i have following data structures
struct a_str { union { struct { struct c_str *c; } b_str; struct { int i; } c_str; }; } struct c_str { struct d_str; } struct d_str { int num; }
i trying access num in struct d_str. reason keep on getting segmentation fault.
struct a_str *a = init_a(); //assume memory allocation , init ok. a->b_str.c->d_str.num = 2;
what wrong?
probably not allocating memory a->b_str.c
in init()
function, may reason a->b_str.c
pointing garbage location , segmentation fault due accessing memory not allocated - illegal memory operation.
if init()
function correct, there should not problem (syntax-wise code correct).
below have suggested inti()
function allocated memory nested structure correctly (read comments).
struct a_str *init() { struct a_str *ret = malloc(sizeof(struct a_str)); // memory `struct a_str` struct c_str *cptr = malloc(sizeof(struct c_str)); // memory inner struct ret->b_str.c = cptr; //assigning valid memory address ret->b_str.c return ret; }
below main()
code steps deallocate/free() dynamically allocated memory.
int main(int argv, char **argc) { struct a_str *ret = init(); ret->b_str.c->d.num = 5; printf("%d\n", ret->b_str.c->d.num); //make sure free memory allocated through malloc free(ret->b_str.c); // 1 first free in struct free(ret); // in reverse order of allocation return 0; }
Comments
Post a Comment