title: C Programming: malloc() for a 2D array (using pointer-to-pointer)
body: <p>yesterday I had posted a question: <a href="https://stackoverflow.com/questions/2838038/c-programming-malloc-inside-another-function">How should I pass a pointer to a function and allocate memory for the passed pointer from inside the called function?</a></p>
  
  <p>From the answers I got, I was able to understand what mistake I was doing.</p>
  
  <p>I'm facing a new problem now, can anyone help out with this?</p>
  
  <p>I want to dynamically allocate a 2D array, so I'm passing a Pointer-to-Pointer from my <code>main()</code> to another function called <code>alloc_2D_pixels(...)</code>, where I use <code>malloc(...)</code> and <code>for(...)</code> loop to allocate memory for the 2D array.</p>
  
  <p>Well, after returning from the <code>alloc_2D_pixels(...)</code> function, the pointer-to-pointer still remains NULL, so naturally, when I try accessing or try to <code>free(...)</code> the Pointer-to-Pointer, the program hangs.</p>
  
  <p>Can anyone suggest me what mistakes I'm doing here?</p>
  
  <p>Help!!!</p>
  
  <p>Vikram</p>
  
  <hr>
  
  <p><strong>SOURCE:</strong></p>
  
  <pre><code>main()
  {
  
  
   unsigned char **ptr;
   unsigned int rows, cols;
  
   if(alloc_2D_pixels(&amp;ptr, rows, cols)==ERROR)      // Satisfies this condition
    printf("Memory for the 2D array not allocated"); // NO ERROR is returned
  
   if(ptr == NULL)                    // ptr is NULL so no memory was allocated
    printf("Yes its NULL!");          
  
   // Because ptr is NULL, with any of these 3 statements below the program HANGS
   ptr[0][0] = 10;                    
   printf("Element: %d",ptr[0][0]);
  
   free_2D_alloc(&amp;ptr);
  
  }
  
  
  signed char alloc_2D_pixels(unsigned char ***memory, unsigned int rows, unsigned int cols)
  {
          signed char status = NO_ERROR;
  
          memory = malloc(rows * sizeof(unsigned char** ));
  
          if(memory == NULL)
          {
              status = ERROR;
              printf("ERROR: Memory allocation failed!");
  
          }
          else
          {
              int i;
  
              for(i = 0; i&lt; cols; i++)
              {
                  memory[i] = malloc(cols * sizeof(unsigned char));
  
                  if(memory[i]==NULL)
                  {
                      status = ERROR;
                      printf("ERROR: Memory allocation failed!");
                  }
              }
  
          }
  
      // Inserted  the statements below for debug purpose only
          memory[0][0] = (unsigned char)10;     // I'm able to access the array from
          printf("\nElement %d",memory[0][0]);  // here with no problems
  
  
          return status;
  }
  
  
  void free_2D_pixels(unsigned char ***ptr, unsigned int rows)
  {
       int i;
  
       for(i = 0; i &lt; rows; i++)
       {
            free(ptr[i]);
       }
  
       free(ptr);
  }
  </code></pre>