I have a problem with a big piece of code, so I reduced it as much as I was able to, in fact I found a solution to my problem, but I'm almost sure there is a better solution, that's why I'm asking for help.
Here's the bad code:
#include <stdio.h>
#include <stdlib.h>
typedef struct{
int a;
}my_struct;
void tab_add(my_struct** tab, int i){
*tab = (my_struct*)realloc(*tab, i+1); // Here's the realloc
printf("Adding struct number %d\n", i);
tab[i]->a = i*8; // Problem here, when accessing tab[i] the second time
printf("Struct added\n");
}
int main(void){
my_struct* tab = NULL;
tab_add(&tab, 0);
tab_add(&tab, 1);
tab_add(&tab, 2);
return 0;
}
The output is:
Adding struct number 0
Struct added
Adding struct number 1
zsh: segmentation fault ./main
Now, here's a code that solve the problem (but it creates a useless variable...):
#include <stdio.h>
#include <stdlib.h>
typedef struct{
int a;
}my_struct;
void tab_add(my_struct** tab, int i){
*tab = (my_struct*)realloc(*tab, i+1);
printf("Adding struct number %d\n", i);
my_struct st; // Useless variable created
st.a = i*8;
(*tab)[i] = st;
printf("Struct added\n");
}
int main(void){
my_struct* tab = NULL;
tab_add(&tab, 0);
tab_add(&tab, 1);
tab_add(&tab, 2);
return 0;
}
Its output is correct:
Adding struct number 0
Struct added
Adding struct number 1
Struct added
Adding struct number 2
Struct added
Thanks for reading :)