Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dynamically Allocate and Store Array of Strings in C

Relatively new to C here. I have a program that reads in a "Dictionary" of words from a text file. Each word in the text file ends with a newline. I would like to dynamically allocate and store an array containing words of a certain length determined by the user. I am not sure that I completely understand how it works. My code doesn’t seem to create this array and only stores the last string that it encounters.

It starts by counting the amount of words of the specified length, then stores that as the "rows" of the array.

My code so far:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

int rows = 0, columns = letterAmount;
while(fgets(word, MAX_CHARS, dictionary)){
    if(strlen(word) == letterAmount + 2){
        rows++;
    }
}

char **wordList = malloc(rows * sizeof(char *));
for(i = 0; i < rows; i++){
    wordList[i] = (char *)malloc(columns + 1);
}

rewind(dictionary);

i = 0;
while(fgets(word, MAX_CHARS, dictionary) && i < rows){
    if(strlen(word) == letterAmount + 2){
        wordList[i] = word;
        i++;
    }
}

Any help is appreciated!

Thanks

>Solution :

You allocate memory but then you leak that pointer by replacing it with a new pointer value. Presumably word is an array on the stack or similar.

// Stores a pointer
wordList[i] = (char *)malloc(columns + 1);

// Stores a new pointer (discards previous value)
wordList[i] = word;

So now, not only have you leaked a whole lot of memory by throwing away pointers, you have also changed every word to point to your word buffer. That’s why you see the output contains only the last word repeated.

What you need to do instead is copy the string. Provided you know that the word is no longer than columns in length, you can do:

strcpy(wordList[i], word);

Note there’s no obvious relationship between columns and MAX_CHARS so it’s hard to advise further on the safety of your memory allocation. I do wonder why you allocate the strings up-front. Why not just allocate them as needed?

wordList[i] = malloc(strlen(word) + 1);
if (wordList[i] != NULL) {
    strcpy(wordList[i], word);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading