Search code examples
carraysmultidimensional-arraydynamic-arrays

Trouble Resizing a 2D Array in C


I have a project where I create a 2D char array that stores words, with the option to add more words, and then resize the array when necessary. I'm getting a variety of errors as I try to play with it and fix it so now I think I need some extra eyes on my code. I'm specifically looking for anything that obviously stands out as an incorrect or troublesome way of allocating memory or initializing an array.

The error I am getting specific to this code says "free(): invalid pointer" and leads to a SIGABRT. Below is my code.

Here is my resize function.

char **  resize_array(char **array) 
{
int i;
char** tmp = malloc(2 * sizeof(*array));
int j;
for(j = 0; j < (2 * sizeof(*array)); j++)
    tmp[j] = malloc(2 * sizeof(*array));

for(i = 0; i < (sizeof *words); i++)
{
    strcpy(tmp[i], words[i]);
}

for(i = 0; words[i] != NULL; i++)
    free(words[i]);
free(words);
return tmp;
}

Here is my resize function being implemented

            int len;
        len = (sizeof words);

    if(upperbound > len) //upperbound keeps track of the word count 
                                 //and resizes the array 
        { 
            char **tmp = resize_array((char **) words);
            int i;
            for(i = 0; i <= upperbound; i++)
                strcpy(words[i], tmp[i]);
        }

And finally here is the "words" array as it is initially initialized.

    char words[14][50];

I'm using VI and running everything on Ubuntu just fyi. Thanks in advance for everyones help!


Solution

  • Inside the resize_array function, you can't determine the previous size of the array using only a pointer to it.

    The call to malloc

    malloc(2 * sizeof(*array))
    

    requests an allocation twice the size of a pointer to a char (only 16 bytes on a 64bit machine).

    This is the first problem you need to fix.