-2
嗨,所以我创建一个程序,使用散列来存储单词和文本文件中出现次数。这按预期工作。我遇到的问题来自释放分配的内存。免费()不释放字符串从结构阵列
这里是我的散列
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#include"hash.h"
/*
struct listnode{
char * word;
int count;
};
*/
void hashCreate(struct listnode * hashTable[], int size){
int i;
for(i=0;i<size;i++){
hashTable[i]=(struct listnode *)malloc(sizeof(struct listnode));
hashTable[i]->count=0;
}
}
int hash(char * data, int size) {
unsigned long hash = 5381;
char * p;
for (p = data; *p != '\0'; ++p) {
hash = (hash * 33) + *p;
}
return (int)(hash % size);
}
void hashAdd(char * data, struct listnode * hashTable[], int size){
int key=hash(data, size);
hashTable[key]->word=strdup(data);
hashTable[key]->count+=1;
}
void hashPrint(struct listnode * hashTable[], int size){
int i;
for(i=0;i<size;i++){
if(hashTable[i]->count!=0)
printf("%s: %d \n",hashTable[i]->word,hashTable[i]->count);
}
}
void hashDelete(struct listnode * hashTable[],int size){
int i;
for(i=0;i<size;i++){
free(hashTable[i]->word);
free(hashTable[i]);
}
}
这就是使用它
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#include"hash.h"
/*
int hash(char * data, int size) {
unsigned long hash = 5381;
char * p;
for (p = data; *p != '\0'; ++p) {
hash = (hash * 33) + *p;
}
return (int)(hash % size);
}
*/
#define SIZE 1500
void removePunct(char * str);
void fileRead(char * filename);
struct listnode * hashTable[1500];
int main(int argc, char ** argv){
int i;
if(argc<2)
fprintf(stderr,"Enter filename \n");
hashCreate(hashTable, SIZE);
for(i=1; i<argc; i++){
fileRead(argv[i]);
}
hashPrint(hashTable,SIZE);
hashDelete(hashTable, SIZE);
return 0;
}
void fileRead(char * filename){
FILE * file = fopen(filename,"r");
char word[80];
if(!file){
fprintf(stderr,"Error opening file \n");
return;
}
while(fscanf(file, "%s", word)==1){
removePunct(word);
hashAdd(word,hashTable,SIZE);
}
fclose(file);
}
void removePunct(char * str){
int i,p=0;
for(i=0; i<strlen(str);i++){
if(isalpha(str[i]) || str[i]==' '){
str[p]=tolower(str[i]);
p++;
}
}
str[p]='\0';
}
在我hashDelete函数的字符串没有被释放,这是造成内存泄漏。我通过释放hashAdd函数中的字符串来测试它,并且没有内存泄漏,但也没有打印字符串。我无法找到不让我释放所有记忆的问题。任何帮助,将不胜感激。
谢谢。我知道它必须非常简单,我没有注意到。这固定了它。 –