0

I'm trying to increase a 2D array with malloc and realloc. I get a segmentation fault.

Here is how I create my tab:

char **tab2D = creerTab2D(taillex, tailley); 


char** creerTab2D(int taillex, int tailley) {

    char **tab2D = malloc( sizeof(char*) * taillex);

    for (int i = 0; i < taillex; i++) {
        tab2D[i] = creerTab1D(tailley);
    }

    return tab2D;
}

Here is how I increase his rows number by 1:

    (*taillex)++;

    *tab = (char**) realloc(*tab, *taillex * sizeof(char*)) ;

    if (*tab == NULL) { printf("Erreur lors du realloc\n"); return;}

    printf("%d", *taillex);

    *tab[*taillex] = malloc(*tailley * sizeof(char)); // Here is the bad access (segmentation fault)

    for (int i = 0; i < *tailley; i++) {
        (*tab)[*taillex][i] = '*';
        printf("%c", (*tab)[*taillex][i]);
    }

This piece of code is inside a function with this prototype (too big to paste here):

void insererCharDansTab2D(char ***tab, int *taillex, int *tailley, int posx, int posy, char c)

I wrote a comment where the segmentation fault appears. Thanks mates!

Paul Bénéteau
  • 775
  • 2
  • 12
  • 36

0 Answers0