1

I need an array of strings in which the length of the array is not known at compile time. what I've done is:

char **words;

words = malloc(capacity * sizeof(char *));

char nextword[MAX_LEN + 1];

while (true) {
    if (num_entries == capacity) {
        capacity += 5;
        realloc(words, (sizeof(char *) * capacity));
    }

    printf("\nEnter a word: ");
    fgets (nextword, MAX_LEN, stdin);

    remove_newline(nextword);

    if (strlen(nextword) == 0) break;

    words[num_entries] = malloc(strlen(nextword + 1));

    if (words[num_entries] == NULL) {
        printf("\nout of space\n");
        break;
    }

    strcpy(words[num_entries], nextword);
    num_entries++;

this seems to work to expand the size once, except that the first element after the expansion has become NULL for some reason. The second time realloc is executed I get an error:

"invalid next size".

2 Answers 2

7

realloc is not guaranteed to give you back the same chunk of memory, because the block that was originally allocated from the heap may not have enough space to accommodate your new requested size. In this case you will get back a new block of memory, with your old data copied to it.

You need to capture the returned value on each loop and use it to check for the data you expect, and also check for it being 0 (if the realloc cannot be done).

words = realloc(words,..)

is an antipattern - avoid this since your old memory can get lost if the realloc fails.

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

Comments

5

Your code is almost there, just need a few modifications. An important thing to remember is that realloc does not modify the value that you pass to it, and it is not required to return the pointer to the same chunk of memory that you passed to it. Here is a working example of using realloc. It is rather straightforward, so you should be able to fix your code by simply following the example.

char **more_words = realloc(words, capacity);
 if (more_words) {
     words = more_words;
 } else {
     // Do something about realloc failure
 }

4 Comments

Thanks for the link. It helped tremendously.
The link is great but in stackoverflow, it is required that you present the solution directly here in case that the link does not work anymore.
@YohanObadia Code is not required, as long as the explanation is sufficient to figure out what the problem is. The solution is presented here by explaining what the problem is (I mean the realloc does not modify the value that you pass to it" part).
Ok I understand what you mean. I just have a real preference for examples and even Wcrousse specified that the link was what helped most. Anyway I will now upvote it :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.