Leem.fin Leem.fin - 2 months ago 10
C Question

pass by reference & assign value to a pointer of pointer of struct

I have a struct

MY_TYPE
:

struct MY_TYPE {
boolean flag;
short int xyz;
};


I have another struct
MY_DATA
which has a field with type of pointer to the above struct:

struct MY_DATA {
MY_TYPE *m_type;
double value;
};


I have a function which takes a pointer to pointer of
MY_DATA
as parameter:

getData(struct MY_DATA **m_data) {
// create a MY_TYPE pointer & assign value to its field
struct MY_TYPE *m_type_tmp = malloc(sizeof(struct MY_TYPE));
m_type_tmp -> xyz = 123;

// I try to assign a value to the MY_TYPE field of m_data,
// there is no compiler error, but run time error "bad access"
(** m_data).m_type = m_type_tmp;
}


I call above function by:

struct MY_DATA *data;
get_data(&data);


The compiler doesn't complain anything, but when run my code, I get "Bad access" on the last line of code of function
get_data(...)
, how come?

Answer

Since you pass the address of an uninitialized pointer, you must allocate the structure MY_DATA as well:

void getData(struct MY_DATA **m_data) {
    // create a MY_TYPE pointer & assign value to its field
    struct MY_TYPE *m_type_tmp = malloc(sizeof(struct MY_TYPE));
    m_type_tmp->flag = 0;
    m_type_tmp->xyz = 123;

    // allocate the MY_DATA structure:
    *m_data = malloc(sizeof(*m_data));
    // Initialize all members
    (*m_data)->m_type = m_type_tmp;
    (*m_data)->value = 0;
}

It would be simpler to have the function return a pointer to the allocated structure:

struct MY_DATA *getData(void) {
    // create a MY_TYPE pointer & assign value to its field
    struct MY_TYPE *m_type_tmp = malloc(sizeof(*m_type_tmp));
    m_type_tmp->flag = 0;
    m_type_tmp->xyz = 123;

    // allocate the MY_DATA structure:
    struct MY_DATA *m_data = malloc(sizeof(*m_data));
    // Initialize all members
    m_data->m_type = m_type_tmp;
    m_data->value = 0;
    return m_data;
}

And invoke it this way:

struct MY_DATA *data = get_data();