I'm writing an application using the C language. I created an new type based on a structure:
typedef struct ENTITY
{
char * field1;
char * field2;
} entity;
Then, I defined a function to dynamically allocate an array of entities:
int my_function(entity ** my_array)
{
count = random_int(1, 10);
entity * result;
result = (entity *) calloc(count, sizeof(entity));
int i;
for(i = 0 ; i < count ; i++)
{
(result+i)->field1 = strdup("Blabla in field1");
(result+i)->field2 = strdup("Blabla in flied2");
// This line print correctly "Blabla in field1" for each element in the array.
printf("->{%s}\n", (result+i)->field1);
}
*my_array = result;
return count;
}
In my main file, I use this function:
entity * my_array;
count = my_function(&my_array);
for(i = 0 ; i < count ; i++)
{
printf("field1 of the element %d: %s\n", i, my_array[i].field1);
}
For some reason, this code works when my array is fulfilled by <= 3 elements, from 4 elements in the array I get a segmentation fault error:
->{Blabla in field1}
->{Blabla in field1}
->{Blabla in field1}
->{Blabla in field1}
field1 of the element 0: `�fZ$
Segmentation fault
I've read a lot about dynamic allocations on here but I can't manage to fix this problem. Any clue?
Thanks for you help!
resultbe anentity **?random_intfunction with literal4). Can you try the same (hardcodeint count = 4) and see if it still fails? If it does, post the minimal compilable code that still shows the problemrandom_intfunction is doing. And may be you are not showing what exactly you are doing.countdeclared?callocandstrduparen't failing and returningNULL? Maybe your simulator is running out of memory somehow?