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

How to properly reallocate an array of strings?

This seems like a simple question and probably a simple answer but I am trying to read in words from a text file and allocate each word to a dynamically allocated array of strings:

char** words = calloc(8, sizeof(char*));

(It must be allocated this way.)

And then I must resize the array as needed. My problem comes when I try to use realloc() for my array. I do it like so:

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

if(index == MAX-1){ // reallocate if needed
    words = (char**) realloc(words, sizeof(*words)*2); MAX*=2;
    printf("Re-allocated %lu character pointers.\n", MAX);
}

Where MAX is the max number of elements that can be stored in the array.

My array is populated with correct values but when realloc is called some strings appear to be missing! Several indexes are not populated anymore and I get a memory error when trying to print the array out as they are missing somehow.

Here is how I allocate the strings and store them at the index:

words[index] = malloc(strlen(temp)+1);
words[index] = strdup(temp); // copy the word over using strdup

What’s going wrong?

>Solution :

For starters this code snippet

words[index] = malloc(strlen(temp)+1);
words[index] = strdup(temp); // copy the word over using strdup

produces a memory leak. You should write at once

words[index] = strdup(temp); // copy the word over using strdup

This statement

words = (char**) realloc(words, sizeof(*words)*2); MAX*=2;

allocates only two pointers of the type char *.

You should write at least

MAX*=2;
words = (char**) realloc(words, sizeof(*words)*MAX); 

Also the condition in the if statement should be

if(index == MAX){

instead of

if(index == MAX-1){

And if you are using the value of MAX then why is there used the magic number 8?

char** words = calloc(8, sizeof(char*));
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