I need to transition from using a fixed size array of pointers to a dynamic one. Currently the code looks like:
struct myType *fixed_bufs[TEST_SZ];
Each element from fixed_bufs is allocated in memory by another module; the pointers to them are just stored in fixed_bufs and eventually freed and another one are added, and so on.
Now, i want to make TEST_SZ dynamic, meaning ( as far as my C knowledge goes ) i will do:
struct myType **bufs;
along with a preliminary allocation of memory for storing just pointers:
bufs = (struct myType **)malloc(TEST_SZ * sizeof(struct myType *));
Does this makes sense and is correct/legal ? My other module is just doing behind the scenes:
struct myType *v1 = malloc(sizeof(struct myType));
v1->a = 1024+i;
v1->b = 2048+i;
and then it stores the pointer in my pointer array:
bufs[i] = v1;
After a certain time, the memory of the elements stored in my list are freed and the my pointer list is repopulated.
I'm asking this because my app is somehow works, but it crashes in a weird way and i can't debug it.
I've created a small demo test app below to better describe the situation Is a memory allocation step that i'm missing ?
I just want to store pointers, the actual data is allocated and freed by the other module, as i've already said.
Here's the code:
#include <stdio.h>
#include <string.h>
struct myType {
int a;
int b;
};
#define TEST_SZ 2048
void fill_data(struct myType **bufs)
{
for (int i = 0; i < TEST_SZ; i++)
{
struct myType *v1 = malloc(sizeof(struct myType));
v1->a = 1024+i;
v1->b = 2048+i;
bufs[i] = v1;
}
}
void empty_data(struct myType **data)
{
for (int i = 0; i < TEST_SZ; i++)
{
free(data[i]);
}
}
int main()
{
struct myType **bufs;
struct myType *fixed_bufs[TEST_SZ];
bufs = (struct myType **)malloc(TEST_SZ * sizeof(struct myType *));
for (int i = 0; i < 100; i++)
{
fill_data(bufs);
fill_data(fixed_bufs);
printf("nth iter: %d => %d %d\n", i, bufs[TEST_SZ-1]->a, bufs[TEST_SZ-1]->b);
printf("fixed_bufs nth iter: %d => %d %d\n", i, fixed_bufs[TEST_SZ-1]->a, fixed_bufs[TEST_SZ-1]->b);
empty_data(bufs);
empty_data(fixed_bufs);
}
}