Maillful Maillful - 23 days ago 7
C Question

free() an array of char**

I have this :

struct Library {
char letter;
int capacity;
int size;
char** words;
};
typedef struct Library Lib;


Initialize the array of Library:

void InitLibrary(Program* startup) {
char alphabet[26] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
startup->dictionary = malloc(sizeof(Lib) * 26);
int i;
for (i = 0; i < 26; i++) {
startup->dictionary[i].letter = alphabet[i];
startup->dictionary[i].capacity = INIT_CAPACITY;
startup->dictionary[i].size = 0;
startup->dictionary[i].words = malloc(sizeof(char*) * startup->dictionary[i].capacity);
}
}


Here i populate the array
words
:

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


and a function like this :

void CleanDico(Program* startup){
int i = 0;
for(; i < startup->dictionary[i].size; i++){
int j = 0;
for(; j < startup->dictionary[i].size; i++){
free(startup->dictionary[i].words[j]);
startup->dictionary[i].words[j] = NULL;
}
startup->dictionary[i].size = 0;
}
startup->totalWords = 0;
}


I got the size of my array on my struct to get the limit of my array, and freed all used cells, but each time I call
CleanDico
, the code crashes. Any suggestions?

I've already asked a question on a problem with a char array. Now I want to
free()
the array. I've read plenty of posts here and there and tested a lot of solutions but none helped me to resolve my problem.

I get a SEGMENTATION_FAULT on
CleanDico
, and I don't have any other informations about the error. Debug mod on Code::Blocks are poor with error messages.

Answer

I think on your second for you meant to do

for(; j < startup->dictionary[j].size; j++){

instead of

for(; i < startup->dictionary[i].size; i++){