'Issue with dynamic C array
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.
Solution 1:[1]
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");
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dbush |
