我实际上正在从事一个有关操作链表的项目,并且一切工作都很好,但是当我用valgrind运行它时,我发现存在很多内存问题。我将代码的一部分放在这里,我认为分配的内存问题是这样,也许您可以帮助我找出来。
因此,我必须读取以下格式的文件:
19971230 20220512 ALklklklk
19970905 20001203 BDHE UNE
20151212 20301123 CLEUSHI
20171221 20301025 DE klkllLU TOPI
20160315 20190227 Ehaaaa
并把它们放在一个链表中,用这个结构表示:
typedef struct cell{
int dateDeb;
int dateFin;
char text[TAILLE_MAX];
struct cell * suivant;
}message;
在一开始,我已经将此函数编码为初始化列表的一个块:
message * creationCellule(){
message * cellule;
cellule = (message *)malloc(sizeof(message));
if(cellule != NULL)
{
cellule -> dateDeb = 0;
cellule -> dateFin = 0;
cellule -> suivant = NULL;
memset(cellule->text, '\0', TAILLE_MAX);
}
return cellule;
}
从文件中读取的功能是这样的:
void lectureFichier(const char * nomFichier, message ** tete)
{
FILE * fp = fopen(nomFichier, "r");
message * test;
test = creationCellule();
if(fp != NULL)
{
while(fscanf(fp,"%d %d ", &(test->dateDeb), &(test->dateFin)) == 2)
{
fgets(test -> text, 100, fp);
insertion(tete, test);
test = creationCellule(test);
}
}
fclose(fp);
}
插入功能是这个:
void insertion(message ** tete, message * cellule){
message ** prec;
if(cellule != NULL){
prec = recherche(tete, cellule -> dateDeb);
cellule -> suivant = *prec;
*prec = cellule;
}
}
Valgrind告诉我内存泄漏,并且动态分配的内存没有释放。没错,因为我没有释放这些函数中的任何内容,但是我不知道在哪里使用free,因为我必须在循环内重用它。这是valgrind结果: enter image description here
您能告诉我一个解决方案如何解决此问题的原因,因为我对此感到困惑。即使我需要函数creationCellule,也可以。没有义务写那个。提前非常感谢您!
答案 0 :(得分:0)
在链接列表创建中没有问题。但是,一旦完成读取文件和链接列表的操作,就需要释放空间。请记住,如果您使用了malloc(),则必须调用free()来释放内存。这样的东西-freeCellule(),您可以在从演讲者Fichier()返回之前调用此函数:
void freeCellule(message *ptr)
{
message * next;
while (ptr) {
next = ptr->suivant;
free(ptr);
ptr = next;
}
}