Jarkko
Jarkko

Reputation: 1

Dynamically allocated array of dynamically allocated strings

I'm learning C after graduation and trying to refresh old skills. I'm currently trying to make a dynamically allocated array that consist of dynamically allocated strings. Below is my code, I am trying to add an adjective to previously initialized array that has the first member as NULL. The last member should always be NULL.

char **addAdjective(char **array, const char *adjective)
{
    int i = 0;
    int count = 0;

    while (*array != NULL){
        array++;
        count += 1;
    }
    array = (char**) realloc(*array, sizeof(*array) * (count+2));

    int adjectiveLength = strlen(adjective);
    array[count] = (char*) malloc(sizeof(const char)*(adjectiveLength + 1));        

    for (i = 0; i < adjectiveLength; i++){
        array[count][i] = adjective[i];
    }
    array[count][i+1] = '\0';


    array[count+1] = NULL;    

    return array;   
}

When I'm calling the above with:

adjectives = addAdjective(adjectives, "beautiful");
adjectives = addAdjective(adjectives, "ugly");
adjectives = addAdjective(adjectives, "sweet");

There seems to be something wrong as when I'm trying to print the array I get nothing..

What could be wrong?

EDIT:

Print function should be okay:

void printAdjectives(char **adjectives)
{
    if (!adjectives)
        return;
    while (*adjectives) {
        printf("%s  ", *adjectives);
        adjectives++;
    }
    printf("\n");
}

And initialization:

char **initAdjectives(void)
{
    char **adjectives = (char **)malloc (1 * sizeof(char *));

    *adjectives = NULL;    

    return adjectives;
}

Upvotes: 0

Views: 99

Answers (1)

Persixty
Persixty

Reputation: 8579

array[count][i+1] = '\0';

ought to be

array[count][i] = '\0';

Or better

array[count][adjectiveLength] = '\0';

Notice that when the code reaches that line i==adjectiveLength. You allocated adjectiveLength+1 characters and writing to i+1 is past the end of the allocated space.

I don't know if that's your only error but it is illegal.

Upvotes: 1

Related Questions