-1

I have a function that dynamically creates a bisimentional array which memorizes a string of words read until "gata" is introduced.

The problem is that it crashes and I think the line

*(*words+*dim-1) = (char*)calloc(MAX_DIM,sizeof(char));

might be one of the problems.What is wrong with this line?

void read_words(char ***words,int *dim)
    {
      char buff[100];
      *words = (char**)calloc(*dim,*dim*sizeof(char*));
      while(strcmp(buff,"gata"))
       {
         printf("the new word : ");
         scanf("%100s", buff);
         if(strcmp(buff,"gata"))
          {
            dim++;
            *words = (char**)realloc(words,*dim*sizeof(char*));
            if(words == NULL)
             {
               printf("Memory allocation failed !\n");
               exit(0);
             }
            *(*words+*dim-1) = (char*)calloc(MAX_DIM,sizeof(char));
            strcpy(*(*words+*dim-1),buff);
          }
       }
    }

int main()
{
  char **words;
  int i,dim = 0;

  read_words(&words,&dim);

  for (i = 0; i < dim; i++)
    free(&words[i]);
  free(words);
  return 0;
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
NickName
  • 13
  • 5

1 Answers1

1

The primary problem is with

  while(strcmp(buff,"gata"))

where buff is an automatic local variable and left uninitialized. Using the contents invoke undefined behavior. You need to initialize buff before using it.

That said,

  • scanf("%100s", buff); opens up the possibility of going off-by-one, make that scanf("%99s", buff);.
  • dim++; increments the pointer itself, not the value pointed to by the pointer.
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • That's not the problem . The dynamic allocation is,and i don't know how to fix it. – NickName Dec 16 '16 at 16:55
  • @NickName : once the pointer is incremented, its value is undefined or meaningless. It can explain a crash as dim is dereferenced `*dim` when the allocation is performed. – francis Dec 16 '16 at 16:58
  • 1
    @francis Thanks for the effort, but as I see from the previous comment from OP it's unlikely to make any effect on _OP_, looks like any other suggestion is not going to be accepted. :) – Sourav Ghosh Dec 16 '16 at 17:00
  • even if i change it with (*dim)++ it still crashes before the line *(*words+*dim-1) = (char*)calloc(MAX_DIM,sizeof(char)); – NickName Dec 16 '16 at 17:02