What exactly am I doing wrong here?
I need to dynamically allocate just enough space for each string on each line.
My teacher said to start with dynamically allocating enough space for 100 lines which I think I did right. Then I assumed next while I'm reading the file I'd take each line and use malloc with enough memory just to store each string.
With my code right now, I run it on Dev-C and it's printing out 104 lines. I run it on gcc and it's printing out 120 lines. I would think since I made memory for 100 lines up top that's all it should print out? (the file I'm reading has about 600 lines but I haven't gotten as far as to keep reallocating more memory)
Code:
int main(){
FILE *fp;
char buffer[50];
char **words;
int i=0;
words = malloc(100 * sizeof(char *) );
if ( (fp = fopen("words.txt", "r" )) == NULL )
{
printf("Couldn't open file\n");
exit(1);
}
while( fgets(buffer, sizeof(buffer), fp))
{
words[i] = malloc(strlen(buffer)*sizeof(char));
strtok(buffer, " \n");
strcpy(words[i], buffer);
printf("%d: %s\n", i+1, words[i]);
i++;
}
getchar();
return 0;
}