Using Double Pointers after memory allocated within function

C is pass by value.

The value assigned to table is lost on returning from InitStringTable().


Also when allocating pointers to char ask for room for pointers to char.

So this:

... = (char**)malloc(sizeof(char)*10);

shall at least be (assuming C):

... = malloc(sizeof(char*)*10);

A possible approach to this would be:

#include <stdlib.h>
#include <string.h>
#include <errno.h>

int InitStringTable(char *** ppptable, const size_t n, const size_t l)
{
   int result = 0;

   if (NULL == ppptable)
   {
     result = -1;
     errno = EINVAL;
   }
   else
   {
     (*ppptable) = malloc(n * sizeof(**ppptable));
     if (NULL == (*ppptable))
     {
       result = -1;
     }
     else
     {
       size_t i = 0;
       for(; i < n; ++i)
       {
         (*ppptable)[i] = calloc(l, sizeof(*(*ppptable)[i]));
         if (NULL == (*ppptable)[i])
         {
           result = -1; 

           /* Failing in the middle requires clean-up. */
           for (; i > 0; --i)
           {
             free((*ppptable)[i-1]);
           }

           free(*ppptable); 
           (*ppptable) = NULL;

           break;
         }
       }
     }
   }

   return result;
 }

Call it like this:

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

int InitStringTable(char *** ppptable, const size_t n, const size_t l);

int main(void)
{
  int result = EXIT_SUCCESS;
  char ** strTable = NULL;

  if ( -1 == InitStringTable(&strTable, 10, 42)) //* Allocate array with 10 "strings" à 42 chars. */
  {
    perror("InitStringTable() failed");
    result = EXIT_FAILURE;
  }
  else
  {
    strcpy(strTable[0], "abcdef");
    strcpy(strTable[1], "xy");
  }

  return result;
}

And no, I won’t get into this ridiculous “You don’t wanna be a 3-star-programmer!” discussion.

Leave a Comment