diff --git a/analyseur.c b/analyseur.c index 99c2815..f60773f 100644 --- a/analyseur.c +++ b/analyseur.c @@ -415,15 +415,22 @@ void analyser_bigrammes(char **lignes, int nb_lignes, char *construire_rapport(const Entree *table, int n) { - char *rapport = malloc((size_t)n * 64 + 256); - char ligne[128]; - rapport[0] = '\0'; - - ajouter(rapport, "rang;mot;occurrences\n"); + size_t capacite = (size_t)n * 64 + 256; + char *rapport = malloc(capacite); + if (rapport == NULL) { + perror("malloc rapport"); + exit(EXIT_FAILURE); + } + size_t position = (size_t)snprintf(rapport, capacite, "rang;mot;occurrences\n"); for (int i = 0; i < n; i++) { - snprintf(ligne, sizeof(ligne), "%d;%s;%d\n", - i + 1, table[i].mot, table[i].occurrences); - ajouter(rapport, ligne); + int taille = snprintf(rapport + position, capacite - position, + "%d;%s;%d\n", i + 1, table[i].mot, table[i].occurrences); + 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; }