user1255365
user1255365

Reputation:

pointer to a structure in a nested structure

I have a 6 levels of nested structures. I am having problem with last three levels. The program compiles fine but when I run it crashes with Segmentation fault. There is some problem in assignment is what I feel. Kindly point out the error.

typedef struct {
    char addr[6];
    int32_t rs;
    uint16_t ch;
    uint8_t ap;
} C;

typedef struct {
      C *ap_info;
} B;

typedef struct {
    union {
        B wi;
    } u;
} A;

function1(char addr , int32_t rs, uint16_t ch, uint8_t ap) {
    A la;
    la.u.wi.ap_info->addr[6] = addr;
    la.u.wi.ap_info->rs = rs;
    la.u.wi.ap_info->ch = ch;
    la.u.wi.ap_info->ap = ap;
}

Upvotes: 0

Views: 295

Answers (2)

Dmitri
Dmitri

Reputation: 9375

You have not allocated memory for the struct pointed to by la.u.wi.ap_info, or set the la.u.wi.ap_info pointer itself. You need something like:

la.u.wi.ap_info = calloc(1,sizeof(C)); // allocate a C instance and 
                                       //  point la.u.wi.ap_info at it

...with a later free(la.u.wi.ap_info); when you no longer need the struct. Or you could point it at a pre-existing struct provided you ensure that the struct you point it to will exist until you're done with it.

Additionally, the line:

la.u.wi.ap_info->addr[6] = addr;

is incorrect; it assigns the character in addr to the seventh element of the array, which only has space for six elements (so it's out of bounds). If addr was meant to be a string you're copying into the structure, then its type should be char * not char, and you need something like:

strncpy(la.u.wi.ap_info->addr, addr, 5); // copy up to 5 chars
la.u.wi.ap_info->addr[5] = '\0'; // explicitly null the sixth char

instead of simple assignment.

Upvotes: 1

Adrian Cornish
Adrian Cornish

Reputation: 23868

You are not allocating memory for the pointers

Upvotes: 0

Related Questions