1

I want to read some words until the word "done" is introduced. These words are put into a dynamically allocated matrix,which is modified at each input received . The problem is that after 3 words the program crashes and the message with "Memory allocation failed" that i put as a warning appears. What is wrong with my reallocation ?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_DIM 100

    int main()
        {
          char **words,buff[100];
          int i,dim = 0;
          words = (char**)calloc(dim,dim*sizeof(char*));
          while(strcmp(buff,"done"))
           {
             printf("the new word : ");
             scanf("%100s", buff);
             if(strcmp(buff,"done"))
              {
                dim++;
                words = (char**)realloc(words,dim*sizeof(char*));
                if(words == NULL)
                 {
                   printf("Memory allocation failed !\n");
                   exit(0);
                 }
                words[dim] = (char*)calloc(MAX_DIM,sizeof(char));
                strcpy(words[dim],buff);
              }
           }
          printf("%d", dim);
          for (i = 0;i < dim;i++)
            free(words[i]);
          free(words);
          return 0;
        }
NickName
  • 13
  • 5
  • 4
    No no no! Indexes are from 0 to n-1, so `words[dim]` is out-of-bounds! – Paul Ogilvie Dec 11 '16 at 13:02
  • 2
    This `scanf("%100s", buff);` should be `scanf("%99s", buff);`. C "strings" need on more `char` to store their `0`-terminator. Or to turn this around: C "strings" provide one `char` less then allocated as they need one `char` to store their `0`-terminator. – alk Dec 11 '16 at 13:05
  • Also `sizeof(char)` equals `1` by defintion. – alk Dec 11 '16 at 13:08
  • OT: All those casts to the allocation functions are useless in C. Just drop them. – alk Dec 11 '16 at 13:08
  • 1
    `words[dim] = (char*)calloc(MAX_DIM,sizeof(char)); strcpy(words[dim],buff);` --> `words[dim-1] = calloc(MAX_DIM, sizeof(char)); strcpy(words[dim-1],buff);` (use `dim-1`) – chux - Reinstate Monica Dec 11 '16 at 17:29

1 Answers1

0

I compiled your code and it kind of worked. The problem I encountered was that after "done" was inputed the program would crash. That can be solved by correcting the last part of your code from

for (i = 0;i < dim;i++)
    free(words[i]);

to

for (i = 0;i < dim;i++)
    free(&words[i]);  
Raphael Sauer
  • 630
  • 1
  • 6
  • 27