Maillful Maillful - 25 days ago 9
C Question

array in a struct and populate him

at the moment i have a project for the studies and me and a friend don't really know on how resolve the problem on a part of this.

So, it's a C project. I have 2 struct :

struct Lib {
char letter;
int capacity;
int size;
char** words[200000];
};
typedef struct Lib Library;
struct Program {
char* loadedFileName[50];
FILE* f;
Library* dictionary;
int totalwords;
};

typedef struct Program Program;


And this function :

void fillDicoFromFile(Program* startup){
rewind(startup->f);
while(!feof(startup->f) && !ferror(startup->f)){
char* word = malloc(sizeof(char) * 30);
fscanf(startup->f, "%s", word);
int indexLib = word[0] - 97;
int sizeLib = startup->dictionary[indexLib].size;
startup->dictionary[indexLib].words[sizeLib] = (char*)malloc(sizeof(char) * (strlen(word)+1));
startup->dictionary[indexLib].words[sizeLib] = word;
startup->dictionary[indexLib].size++;
free(word);
}
CountTotalWords(startup);
}


startup->dictionary is a array of 26 Library, and when i get a word from the file, i check his first letter and select the good Library (startup->dictionary[0] for 'a' ...) and then put the word on the array "word" of the struct, but when i want printf some words, it's bugged strings or wrongs one. I'm pretty sure we're doing wrong on pointers but where ...

What are we doing wrong ?

Answer

This:

    startup->dictionary[indexLib].words[sizeLib] = (char*)malloc(sizeof(char) * (strlen(word)+1));
    startup->dictionary[indexLib].words[sizeLib] = word;

... doesn't do what you think it does. You are allocating space (using malloc, the first line), but you are not using it; instead, you are storing a pointer to the previously allocated space in word (the second line). To be clear, the statement startup->dictionary[indexLib].words[sizeLib] = word will not copy a string; it is just assigning a pointer.

Then, you free that space:

    free(word);

The dictionary now contains a dangling pointer - a pointer to an area that is no longer allocated. The fix is easy:

  1. Remove the first line above (which uses malloc); you don't need to allocate space for a word that you've already allocated space for
  2. Remove the free(word) line; you don't want to deallocate this space, since it is being referred to by the dictionary structure.