0

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;
}
2
  • 2
    You should include the print function too, there could be a bug there. Commented Mar 20, 2015 at 16:04
  • Also, how is adjectives initially allocated? Commented Mar 20, 2015 at 16:06

1 Answer 1

1
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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Dan for your answer. Unfortunately it did not solve my problem :/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.