0

I'm just having problems getting strings from a file. The strings are listed one per line and limited by the new line character. I'm trying to store them in a dynamic array of strings and received an invalid next size error and then aborted after the third string.

I'm using a structure Dictionary to store the size in an integer variable and the words in an array of strings.

The code is:

struct Dictionaries {
    char** words;
    int size;
};
typedef struct Dictionaries dictionary;

dictionary get_dict (FILE* fp) {
    dictionary* dict  =  malloc(sizeof(dictionary));
    dict->size = 0;
    int strSize = 0;
    dict->words = (char**) malloc(sizeof(char*));
    dict->words[dict->size] = malloc(sizeof(char));

    while(1) {
        char c = fgetc(fp);

        if (c == EOF ){
            break;
        }

        if (c == '\n') {
            dict->words[dict->size][strSize] = '\0';
            strSize = 0;
            dict->size++;
            dict->words[dict->size] = malloc(sizeof(char));
            dict->words = (char**) realloc(dict->words, (dict->size+1) * sizeof(char*));

        } else {
            strSize++;
            //printf("%d\n", strSize);
            //printf("%d\n", dict->size);
            dict->words[dict->size] = (char*) realloc(dict->words[dict->size], (strSize+1) * sizeof(char));
            dict->words[dict->size][strSize -1] = c;
        }
    }
    return *dict;
}

PS sorry for the poor formatting, my first time using this site.

mch
  • 9,424
  • 2
  • 28
  • 42
Joe Nissen
  • 11
  • 1
  • 2
    `c` should be declared as int. EOF does not fit in char – klutt Aug 25 '21 at 12:41
  • You should `realloc` `dict->words` first before you `malloc` something for `dict->words[dict->size]`. – mch Aug 25 '21 at 12:44
  • 1
    You really should return the `dict` pointer, instead of `*dict`. – wildplasser Aug 25 '21 at 13:10
  • The simplicity of reading content from a file into dynamically allocated memory, eg, suitable for strings is being obfuscated by a `char **` member of a `struct *`. Suggest stripping away these confusion factors until the fundamental task (which you have said is: _"getting strings from a file."... "...to store them in a dynamic array of strings"_), is understood, and accomplished. Only then work on making adaptations to use some form of `struct` container. – ryyker Aug 25 '21 at 17:22
  • inside the loop, `dict->words[dict->size] = malloc(sizeof(char));` writes out of bounds , you need to do the following realloc before doing this line – M.M Aug 25 '21 at 22:58

0 Answers0