【发布时间】:2016-05-01 03:38:23
【问题描述】:
我正在编写的 wf 函数中泄漏了非常少量的内存,我似乎无法准确定位它。我正在使用哈希表来保存频率,但我的测试使它看起来好像不在哈希函数中。这是我打开/读取文件并在最后释放数据的功能。我确定这是一个简单的错误,但我查看这段代码太久了,无法看到它。
typedef struct {
int noInFiles, numFiles, numToPrint;
char** fileNames;
FILE** files;
Hash hash;
} Freq;
void handleInput(int argc, char* argv[], Freq* freq) {
int num = 0, i, j = 0;
char* crap;
printf("memcurrent pre fileName alloc: %d\n\n", memCurrent());
freq->fileNames = calloc(argc - 1, sizeof(char**));
printf("memcurrent post filename alloc: %d\n\n", memCurrent());
freq->numToPrint = 10;
if(argc < 2) {
freq->noInFiles = 1;
freq->numFiles = 0;
return;
}
for(i = 1; i < argc; i++) {
if(argv[i][0] == '-') {
if(argv[i][1] == 'n') {
num = strtol(argv[i] + 2, &crap, 10);
freq->numToPrint = num;
}
else {
fprintf(stderr, "Usage: wf [-nX] [file...]\n");
exit(EXIT_FAILURE);
}
}
else {
freq->fileNames[j] = calloc(strlen(argv[i]) + 1 ,sizeof(char));
strcpy(freq->fileNames[j], argv[i]);
j++;
freq->numFiles++;
}
}
}
void openFiles(Freq* freq) {
int i;
char* str;
printf("Memcurrent pre open: %d\n",memCurrent());
freq->files = calloc(freq->numFiles,sizeof(FILE**));
printf("Memcurrent post open: %d\n",memCurrent());
for(i = 0; i < freq-> numFiles; i++) {
freq->files[i] = fopen(freq->fileNames[i],"r");
if(freq->files[i] == NULL) {
str = malloc(strlen(freq->fileNames[i]) + 5);
sprintf(str,"wf: %s",freq->fileNames[i]);
perror(str);
free(str);
exit(EXIT_FAILURE);
}
}
}
void freeFreq(int argc, Freq* freq) {
int i;
for(i = 0; i < argc - 1 ; i++) {
free(freq->fileNames[i]);
}
free(freq->fileNames);
free(freq->files);
}
哈希函数
typedef struct {
Entry* arr;
int size, numValid;
} Hash;
void initHash(Hash* hash) {
hash->arr = calloc(BASESIZE, sizeof(Entry));
TOTALALLOC =+ (BASESIZE * sizeof(Entry));
hash->size = BASESIZE;
hash->numValid = 0;
}
void freeTable(Hash* hash) {
int i;
for(i = 0; i < hash->numValid - 1; i++) {
if(hash->arr[i].correct == 1 && hash->arr[i].valid == 1) {
wordsFreed++;
free(hash->arr[i].word);
}
}
free(hash->arr);
}
【问题讨论】:
-
应该是
strtol(argv[i] + 1,而不是+2? -
什么是
Hash?请提供一个可编译的示例。 -
Quibble:
calloc(..., FILE**)应该是 FILE*(一个 *)。 -
@AustinHastings 不,该值工作正常,它得到一个格式为 [-nX] 的输入标志,其中 X 是我想要的值
-
@EvanCooper “该值运行良好” 您可以摆脱它,因为
sizeof(FILE*)恰好与您平台上的sizeof(FILE**)相同。正确的表达式是sizeof(FILE*)和sizeof(char*)。您确实知道在分配不是指针的数组时如何正确调用calloc,为什么在这种情况下添加一个虚假的星号?
标签: c memory-leaks