\n","author":{"@type":"Person","name":"Mathew Cherian"},"upvoteCount":0,"answerCount":1,"acceptedAnswer":{"@type":"Answer","text":"
The errors happen because you have array overflow. Change
\nif(word_count > word_alloc)\n
\nto
\nif(word_count >= word_alloc)\n
\nto fix it.
\n","author":{"@type":"Person","name":"Weather Vane"},"upvoteCount":1}}}Reputation: 35
I am working on a HW assignment dealing with a dynamically allocated array that can handle different sized input files. My issue is that a pair of (null) values keep appearing tied to the word_alloc variable (changing it moves where in the output the (null) appears). How do I fix this?
int main(int argc, char *argv[]) {
char str[80];
int word_alloc = 0;
int word_count = 0;
char **str_array;
FILE *file;
file = fopen("hw3-data.txt", "r");
// Allocate memory to the array of strings (char arrays)
word_alloc = 10;
str_array = (char **) malloc(sizeof(char*) * word_alloc);
while (fscanf(file, "%s", str) != EOF) {
//doubles the word_alloc/str_array if we have more words than allocated
if(word_count > word_alloc) {
word_alloc *= 2;
str_array =(char **) realloc(str_array, sizeof(char*) * word_alloc);
}
str_array[word_count] = (char *) malloc(sizeof(char) * (strlen(str) + 1));
strcpy(str_array[word_count], str);
++word_count;
}
return 0;
}
Upvotes: 0
Views: 34
Reputation: 34583
The errors happen because you have array overflow. Change
if(word_count > word_alloc)
to
if(word_count >= word_alloc)
to fix it.
Upvotes: 1