Construire le rapport sans reparcourir le prefixe

This commit is contained in:
2026-10-07 10:37:04 +02:00
parent 6ab37d60ee
commit 1d0757868d
+15 -8
View File
@@ -415,15 +415,22 @@ void analyser_bigrammes(char **lignes, int nb_lignes,
char *construire_rapport(const Entree *table, int n) char *construire_rapport(const Entree *table, int n)
{ {
char *rapport = malloc((size_t)n * 64 + 256); size_t capacite = (size_t)n * 64 + 256;
char ligne[128]; char *rapport = malloc(capacite);
rapport[0] = '\0'; if (rapport == NULL) {
perror("malloc rapport");
ajouter(rapport, "rang;mot;occurrences\n"); exit(EXIT_FAILURE);
}
size_t position = (size_t)snprintf(rapport, capacite, "rang;mot;occurrences\n");
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
snprintf(ligne, sizeof(ligne), "%d;%s;%d\n", int taille = snprintf(rapport + position, capacite - position,
i + 1, table[i].mot, table[i].occurrences); "%d;%s;%d\n", i + 1, table[i].mot, table[i].occurrences);
ajouter(rapport, ligne); if (taille < 0 || (size_t)taille >= capacite - position) {
fputs("Rapport trop long\n", stderr);
free(rapport);
exit(EXIT_FAILURE);
}
position += (size_t)taille;
} }
return rapport; return rapport;
} }