J
J
julien_sorel2015-04-14 15:47:59
C++ / C#
julien_sorel, 2015-04-14 15:47:59

How to add a string to a dynamic array of strings in SI?

I am writing a function that adds a string to an array of strings.

char **add_string(char **array, const char *string)
{
    int i = 0;
    while (array[i] != NULL){        
        i++;
    }
    array = realloc(array, (i + 1) * sizeof(char *));
    array[i] = malloc((strlen(string) + 1));
    strcpy(array[i], string); 
    return array;
}

The function works, but Valgrid returns -- Invalid read of size 8, 29 bytes are definitely lost in 5 blocks.
Thank you in advance.
Initially, the array itself is initialized like this:
char **init_array(void)
{
char **array = malloc(sizeof(char *));
array[0] = NULL;
return array;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2015-04-14
@jcmvbkbc

array = realloc(array, (i + 1) * sizeof(char *));
    array[i] = malloc((strlen(string) + 1));

Since you are marking the last element of the array with NULL, this code should look like this:
array = realloc(array, (i + 2) * sizeof(char *));
    array[i] = malloc((strlen(string) + 1));
    array[i + 1] = NULL;

Without this, after the first element is added, the search loop will look outside of array.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question