Is there a correct way to use realloc, for when you want to add words of variable size to a string array? I am getting a segmentation fault. Please show me what's wrong
// This function puts every word found in a text file, to a String array, **words
char **concordance(char *textfilename, int *nwords){
FILE * fp;
char *fileName = strdup(textfilename);
fp = fopen(fileName, "r");
if(fp == NULL) {
perror("fopen");
exit(1);
}
char **words = malloc(sizeof(char));
// char **words = NULL
char line[BUFSIZ];
while(fgets(line, sizeof(line), fp) != NULL){
char *word = strdup(line);
word = strtok(word, " ");
do{
words = realloc(words, (*nwords+1) * sizeof(char(*)));
words[*nwords] = word;
} while((word = strtok(NULL, " ")) != NULL);
}
return words;
}
int main(int argc, const char * argv[]) {
int *nwords = malloc(sizeof(int));
nwords = 0;
concordance("test.txt", nwords);
}
char **words = malloc(sizeof(char));looks fishy to mechar **wordsshould be allocated to size of pointer and to the maximum number of pointers you want to store, e.g.char **words = malloc(sizeof(char *)*1000);for a maximum of 1000 pointers.strtok()unless you really know what you’re doing, because it modifies the string you’re scanning replacing the delimiter with a null.