Pregunta

Here is the code I tried,Segmentation fault was the result..

void allocate(int ** universe,int n)              // to assign pointer "a"  a nXn matrix 
{

   universe=(int **) calloc(n,sizeof(int *));
   int l;
   for(l=0;l<n;l++)
   universe[l]=(int *)calloc(n,sizeof(int));
   int u;
   for(l=0;l<n;l++)
   for(u=0;u<n;u++)      //making all entries 00
   universe[l][u]=0;
}
¿Fue útil?

Solución

Whats wrong in the following function?

Since arguments are passed by value, your function works on a copy of the passed-in pointer, and doesn't modify the pointer in the caller, that remains uninitialised (or still points where it pointed before), and you can't access the allocated memory from the caller, and trying to access it via universe[i][j] is likely to cause a segmentation fault. As a further consequence, when allocate() returns, you have lost the only pointers to the allocated memory and that's a leak.

The correct way to do it is to

  • return the pointer,

    int ** allocate(int n)
    {
        int **universe = calloc(n,sizeof(int *));
        if (!universe) {
             fputs(stderr, "Allocation of universe failed.");
             exit(EXIT_FAILURE);
        }
        int l;
        for(l = 0; l < n; l++) {
            universe[l] = calloc(n,sizeof(int));
            if (!universe[l]) {
                fprintf(stderr, "Failed to allocate row %d.\n", l);
                exit(EXIT_FAILURE);
            }
        }
        return universe;
    }
    

    and call that like int **universe = allocate(124);, or

  • pass in the address of the pointer you want to allocate memory to,

    void allocate(int *** universe_addr,int n)        // to assign pointer "a"  a nXn matrix 
    {
        int ** universe = calloc(n,sizeof(int *));
        if (!universe) {
            /* repair or exit */
        }
        int l;
        for(l = 0; l < n; l++) {
            universe[l]=(int *)calloc(n,sizeof(int));
            if (!universe[l]) {
                /* repair or exit */
            }
        }
        /* Now set the pointer in the caller */
        *universe_addr = universe;
    }
    

    and call it like allocate(&universe, 123);.

Note: I have removed the initialisation loop, since calloc already zeros the allocated memory, hence it is unnecessary to set it to 0 again.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top