Valgrind 检查的 C 程序:不能 return 所有保留存储 space

C programm by Valgrind check: can't return all the reserved storage space

我有以下使用字符串和数组从 csv 文件输出 txt 文件的代码,库 "input3.h" 是将文件输出到 TXT 的代码。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "input3.h"

/* Die Konstanten:
 *  int MAX_LAENGE_STR - die maximale String Länge
 *  int MAX_LAENGE_ARR - die maximale Array Länge
 *  sind input3.c auf jeweils 255 und 100 definiert
 */

int main(int argc, char **argv) {
    if (argc < 3) {
        printf("Aufruf: %s <anzahl> <bundesland>\n", argv[0]);
        printf("Beispiel: %s 100 Bayern\n", argv[0]);
        printf("Klein-/Großschreibung beachten!\n");
        exit(1);
    }
    int anzahl = atoi(argv[1]);
    char *bundesland = argv[2];

    // Statisch allokierter Speicher
    char staedte[MAX_LAENGE_ARR][MAX_LAENGE_STR];
    char laender[MAX_LAENGE_ARR][MAX_LAENGE_STR];
    int bewohner[MAX_LAENGE_ARR];

    int len = read_file("staedte.csv", staedte, laender, bewohner);

    // Hier implementieren
    char ** jg;
    int cc = 0;
    int cc_jg = 0;

    for(int i = 0; i < len; i++) {
        if((strcmp(bundesland, laender[i]) == 0) && (bewohner[i] >= anzahl)) {
            cc ++;
        }
    }

    jg = (char **) malloc(MAX_LAENGE_ARR*sizeof(char *));;
    for (int j = 0; j < len; j++) {
        jg[j] = (char*)malloc(MAX_LAENGE_STR*sizeof(char));
    }

    for(int i = 0; i < len; i++) {
        if((strcmp(bundesland, laender[i]) == 0) && (bewohner[i] >= anzahl)) {
            sprintf(jg[cc_jg], "Die Stadt %s hat %d Einwohner.", staedte[i], bewohner[i]);
            cc_jg++;
        }
    }

// Mithilfe von write_file(...) soll das Ergebnis in die "resultat.txt"
    write_file(jg, cc_jg);

    // Dynamisch allozierter Speicher muss hier freigegeben werden.
    for(int l = 0; l < cc; l++) {
        free(jg[l]);
    }
    free(jg);
    return 0;
}

我的问题是,如果这个程序被 Valgrind 检查,它说这个程序不能 return 所有保留存储 space,我不明白为什么这个问题存在.

你 运行 malloc jg[j] len 次,但只释放它 cc 次。

正确的做法是:

for(int l = 0; l < len; l++) {
        free(jg[l]);
    }