0

I'm trying to make a dynamic char array, but I'm running into issues. I get segmentation fault when I try to add anything to the array.

static int arrays()
   {
    int INITIAL = 1;
    char **all_words;
    all_words = (char**)malloc(INITIAL*sizeof(*all_words));
    int currentSize = INITIAL;

    for(int i = 0; i < counter; i++){
        all_words = realloc(all_words,currentSize*sizeof(*all_words));
        strcpy(all_words[i], "hello");
        currentSize++;
    }
    for(int i = 0; i < counter; i++){
        printf("%s ", all_words[i]);
    }

}

I pretty much copied this from a guide online, so I'm not sure why it wouldn't work.

4
  • 1
    Don't forget to check that your malloc and realloc succeeded. Commented Mar 10, 2022 at 18:50
  • 1
    Are you trying to have a dynamic array of strings, or a dynamic array of char (holding one string)? Commented Mar 10, 2022 at 18:51
  • Dynamic array of strings Commented Mar 10, 2022 at 18:52
  • Why is INITIAL = 1 when you put nothing in the array? You should start at 0 with all_words = NULL. Increment currentSize before the realloc. Next replace strcpy with strdup so you actually allocate memory for the strings. Commented Mar 10, 2022 at 23:25

1 Answer 1

3

You've correctly allocated an array of char *, however those pointers remain uninitiaized. So when you then do this:

strcpy(all_words[i], "hello");

You're dereferencing an invalid pointer.

Each element of all_words needs to point to allocated space. This simplest way to do this is to use strdup if your system supports it instead of strcpy:

all_words[i] = strdup("hello");

Otherwise you would use malloc to allocate the space, then use strcpy

all_words[i] = malloc(sizeof("hello"));
strcpy(all_words[i], "hello");
Sign up to request clarification or add additional context in comments.

2 Comments

Interesting. I recently did this with a struct called Words. Why didn't I need to allocate for every single index for that? array = (Words*)realloc(array, sizeof(Words)*++n); This was enough to do it.
@code1331 Because a struct (assuming Words is a struct) is not a pointer. When you have an array of pointers, those pointers still need to be set to a valid value before they can be dereferenced.

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.