bgarrood
bgarrood

Reputation: 497

How to dynamically allocate array of structs inside a function in C

I am trying to dynamically size an array of struts inside a function which is reading data in from a file, so I do not know size at compile time.

I am getting an error when populating the dynamically allocated arrays "Exception thrown: write access violation) in the main on one of the lines assigning values to this array on a (seemingly)random index, like i=170 in (mystruct_array)[i].b = i in main, suggesting that I am not correctly allocating the memory in the function. I have searched here but can't find what I am doing wrong - I appreciate it is probably something trivial I am missing. So, please, what am I doing wrong here?

#define ELEMENT_COUNT   10000

typedef struct mystruct
{
    uint64_t a;
    uint64_t b;
    uint64_t c;
} mystruct_t;

void test(mystruct_t ** p_struct_array, uint32_t * p_count)
{
    *p_count = ELEMENT_COUNT;
    *p_struct_array = malloc(ELEMENT_COUNT * sizeof(mystruct_t *));
}

void main()
{
    mystruct_t * mystruct_array = NULL;
    uint32_t count;
    test(&mystruct_array, &count);
    for (uint64_t i = 0; i < ELEMENT_COUNT; i++)
    {
        (mystruct_array)[i].a = i;
        (mystruct_array)[i].b = i;
        (mystruct_array)[i].c = i;
    }
    getch();
}

Upvotes: 0

Views: 140

Answers (1)

Nate Eldredge
Nate Eldredge

Reputation: 58473

*p_struct_array = malloc(ELEMENT_COUNT * sizeof(mystruct_t *));

should be

*p_struct_array = malloc(ELEMENT_COUNT * sizeof(mystruct_t));

You want to allocate an array of 10000 mystruct_ts, not 10000 pointers.


Many people suggest avoiding bugs like this by always following a pattern like

ptr = malloc(count * sizeof(*ptr));

which in your case would read

*p_struct_array = malloc(ELEMENT_COUNT * sizeof(**p_struct_array));

and indeed the type of **p_struct_array is mystruct_t, not mystruct_t *.

Upvotes: 2

Related Questions