0

I'm trying to pass a pointer to a pointer to a procedure, but i get a segfault everytime, while passing it to a function works perfectly fine. I guess it may have something to do with the coercion C does automatically on arrays to pointers, such as in this question : passing a pointer to a pointer in C .

But i don't know how to fix it.

Here's the code :

#include <stdio.h>
#include <stdlib.h>

void creer_matrice(int nbCol, int nbLigne, char **matrice)
{
     int i,j;

     matrice = calloc( nbCol, sizeof(char*));

     if( matrice == NULL ){

         printf("Allocation impossible");
         exit(EXIT_FAILURE);

     }

     for( i = 0 ; i < nbLigne ; i++ ){

          matrice[i] = calloc (nbCol, sizeof(char*));

            if( matrice[i] == NULL ){

             printf("Allocation impossible");
             exit(EXIT_FAILURE);

             }
      }


      /* Remplissage de test*/
     for(i = 0; i < nbLigne; i++){

           for(j = 0; j < nbCol; j++){
             matrice[i][j] = 'I';
           }

     }

   //return matrice;
}


int main(){
    int i,j;

    char **matrice;

    creer_matrice(8,6,matrice);

    //matrice = creer_matrice(8,6);

      for(i = 0; i < 6; i++){
         for(j = 0; j < 8; j++){
            printf("%c ",matrice[i][j]);
         }
      printf("\n");
      }

}

Can somebody please tell me where i am wrong and how to solve it ?

Community
  • 1
  • 1
Prewitt
  • 33
  • 2
  • 10

2 Answers2

0
matrice = calloc( nbCol, sizeof(char*));

Here you're not allocating enough memory for your matrix. You need to allocate the memory depending on the size of your matrix and the type you store in it:

matrice = calloc(nbCol * nbLigne, sizeof(int));

And remove

matrice[i] = calloc (nbCol, sizeof(char*));

Try to do as less system calls as possible. If you can allocate all matrix in a single call, do it. You already know the exact size to be allocated at the start of your function.

And don't forget to free your allocated memory once you're finished.

free(matrice);
m0skit0
  • 25,268
  • 11
  • 79
  • 127
0

Change this lines:

 for( i = 0 ; i < nbLigne ; i++ ){

      matrice[i] = calloc (nbCol, sizeof(char*));

To:

 for( i = 0 ; i < nbCol ; i++ ){

      matrice[i] = calloc (nbLinge, sizeof(char));

Or event better: allocate memory for whole matrix in one statement.

yattering
  • 436
  • 4
  • 7