-1

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 ?

Maillful
  • 77
  • 1
  • 6
  • 1
    We need a full source example, including inputs and outputs – KevinDTimm Nov 11 '16 at 23:02
  • `char** words[]` looks fishy. What do you want to accomplish? Anyway, you don't cast the correct type. Pay heed to compiler warnings and crank them up. Also don't cast the result of `malloc` & friends or `void *` in general. – too honest for this site Nov 11 '16 at 23:11

1 Answers1

0

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.
davmac
  • 20,150
  • 1
  • 40
  • 68
  • Ok, that's why we had some troubles, now i see what we're doing it wrong, thank you for your reply :D – Maillful Nov 11 '16 at 23:20