I'm working on making a C program that basically can take a sentence and count how many times each word appears in it. I've made a stripped down version that reproduces the issue exactly.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct testStrut{
char * string;
int uses;
}word;
void grow();
int main(){
int i;
int count = 1;
word ** words;
words = (word **) malloc(count * sizeof(word *));
words[0] = (word *) malloc(sizeof(word));
for(i = 0; i < 10; i++){
printf("Re-looping i: %d \n", i);
printf("words[0]->string = %s \n", words[0]->string);
grow("TEST", words, &count);
}
printf("Done.");
return 0;
}
void grow(char * str, word ** words, int * count){
word ** tmp;
tmp = realloc(words, (*count) * sizeof(word *));
if(tmp){
tmp[(*count)-1] = malloc(sizeof(word));
tmp[(*count)-1]->string = malloc(strlen(str)+1); /*+1 for null terminator as pointed out */
strcpy(tmp[(*count)-1]->string, str);
tmp[(*count)-1]->uses = 1;
words = tmp;
(*count)++;
} else{
printf("Failure to allocate. \n");
exit(0);
}
printf("Count: %d and word[0] %s \n", (*count), str);
}
As well as the output from a run:
Re-looping i: 0
words[0]->string = (null)
Count: 2 and word[0] TEST
Re-looping i: 1
words[0]->string = TEST
Count: 3 and word[0] TEST
Re-looping i: 2
words[0]->string = TEST
Count: 4 and word[0] TEST
Re-looping i: 3
words[0]->string = TEST
Count: 5 and word[0] TEST /*Prints it fine? */
Re-looping i: 4
Segmentation fault (core dumped) /*Suddenly unable to print it? */
I'm not understanding why between ending the grow function and re-going through the loop the value of words[0]->str is suddenly lost. Is there something I'm missing?
[I do know that I should be freeing anything I malloc.I also realize my method prototype isn't the correct one but I just wanted to make a quick program that demonstrated my issue]