循环调用malloc引发Valgrind检测内存泄漏的解决咨询
Let's tackle those Valgrind memory leaks and file handling issues head-on. I’ve gone through your problem description, and here’s how to fix each issue with concrete code changes:
1. Fix the Unfreed Node in lectureFichier()
The root issue here is that you’re creating a node with creationCellule() before attempting to read data. If the read fails (e.g., hitting EOF), that unused node gets abandoned without being freed. Adjust your loop logic to handle this case explicitly:
Cellule *lectureFichier(const char *nomFichier) { Cellule *head = NULL; FILE *file = fopen(nomFichier, "r"); if (!file) { perror("Erreur ouverture fichier"); return NULL; } while (1) { // Créer un nouveau noeud avant la lecture Cellule *nouvelleCellule = creationCellule(); if (!nouvelleCellule) { perror("Erreur allocation mémoire"); break; } // Tenter de lire les données dans le noeud if (fscanf(file, "%s %d", nouvelleCellule->message.texte, &nouvelleCellule->message.id) == EOF) { // Lecture échouée : libérer le noeud inutilisé free(nouvelleCellule); break; } // Lecture réussie : insérer dans la liste insertion(&head, nouvelleCellule); } // N'oubliez pas de fermer le fichier ! (voir point 3) fclose(file); return head; }
2. Fix Memory Leaks in suppression()
Your current suppression() function only removes the node from the linked list but doesn’t free the memory allocated by malloc. You need to free the node’s memory after adjusting the list pointers:
void suppression(Cellule **head, int idCible) { if (!head || !*head) return; Cellule *courant = *head; Cellule *precedent = NULL; // Rechercher le noeud à supprimer while (courant && courant->message.id != idCible) { precedent = courant; courant = courant->suivant; } if (!courant) return; // Noeud non trouvé // Sauvegarder le noeud suivant avant de libérer le courant Cellule *suivant = courant->suivant; // Libérer la mémoire du noeud free(courant); // Ajuster les pointeurs de la liste if (!precedent) { *head = suivant; // Suppression du premier noeud } else { precedent->suivant = suivant; } }
3. Fix Unclosed File Handles
You mentioned opening files but not closing them—this causes file descriptor leaks, which Valgrind flags as errors. Always pair fopen() with fclose() at the end of your file operations, even if an error occurs (use fclose() after handling errors, as shown in the lectureFichier() example above).
After applying these changes, recompile your code and run Valgrind again. The ERROR SUMMARY:213 errors from 19 contexts should drop to 0 once all memory leaks and file descriptor issues are resolved.
内容的提问来源于stack exchange,提问作者Jamin

