Проблема:
В этом примере кода выполняется поиск слов и подсчет количества слов и количества уникальных слов для больших текстовых файлов с тысячами строк. Я получаю сообщение об ошибке, любоеидеи?
ОШИБКА:
week7_14(43430,0x1087085c0) malloc: *** error for object 0x696c617274737561: pointer being freed was not allocated
week7_14(43430,0x1087085c0) malloc: *** set a breakpoint in malloc_error_break to debug
Пример кода:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLEN 100
#define MAXWORDS 1000
int findWord(char *word[], char *temp, int index) {
for (int i=0; i<index; i++)
{
if (strcmp(word[i], temp) == 0) // found the word
return 1;
}
return 0; // cannot find word }
int main(int argc, char **argv) {
char filename[MAXLEN];
char *words[MAXWORDS] = {NULL};
char temp[MAXLEN];
int wordCount = 0;
int uniqueWordCount = 0;
int i = 0;
// read in the filename
printf("insert a file name: (eg. test.txt)\n");
scanf("%s", filename);
FILE *fp = fopen(filename, "r");
if (fp == NULL)
{
printf("Cannot open file %s\n", filename);
return 1;
}
while ((fscanf(fp, "%s", temp) == 1) && uniqueWordCount<MAXWORDS)
{
wordCount++; // update total number of words
// find word in words array
if (!findWord(words, temp, uniqueWordCount))
{
words[uniqueWordCount] = calloc(strlen(temp)+1,
sizeof(char));
if (words[uniqueWordCount] == NULL)
{
printf("calloc failed to allocate memory\n");
return 1;
}
strcpy(words[uniqueWordCount], temp);
uniqueWordCount++; // update number of unique words
}
}
fclose(fp);
while (i<uniqueWordCount)
{
free(words[uniqueWordCount]);
i++;
}
printf("Total number of words = %d\n", wordCount);
printf("Number of unique words = %d\n", uniqueWordCount);
return 0; }
Примертекстовый файл, который работает (test.txt):
Any girl jumped over one boy.
Some car skipped to some boy.
One town drove over the town.
Any town ran under some dog.
Some girl drove to a town.
The boy walked under any town.
A town jumped over any car.
Any boy jumped from a car.
A dog ran over a boy.
A girl ran to some car.
A car ran under the girl.
The car ran on any town.
One dog walked under any dog.
A car jumped on some town.
A boy ran to a boy.
The dog drove over a boy.
A boy jumped over the car.
Some car drove on some girl.
One boy drove under some girl.
A girl walked over some dog.
Вывод:
вставить имя файла: (например, test.txt)
test.txt
Общее количество слов = 120
Количество уникальных слов = 30