Home > Software engineering >  How to properly reallocate an array of strings?
How to properly reallocate an array of strings?

Time:04-30

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:

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?

CodePudding user response:

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*));
  • Related