简体   繁体   English

无法释放程序中的所有 malloc 和 realloc 调用

[英]Can't free all malloc and realloc calls in program

In my program I have a few malloc and realloc calls but for some reason when I call free on the ones that I called it still points to them as having direct leaks.在我的程序中,我有一些 malloc 和 realloc 调用,但由于某种原因,当我对我调用的那些调用 free 时,它仍然指向它们存在直接泄漏。

The variable name was declared earlier as char **names and wasn't initialized until below.变量名早先被声明为 char **names 并且直到下面才被初始化。 I reallocating and allocating names under different parameters so I am not sure how to free that at the end.我在不同的参数下重新分配和分配名称,所以我不确定最后如何释放它。 Would I just iterate through the entire names array once?我会遍历整个名称数组一次吗? Or do I have to do it multiple times?还是我必须多次这样做?

names = malloc(size * sizeof(char *));   //MALLOC
names[0] = malloc(2 * sizeof(char));     //MALLOC
names[0] = "0\0";
names[1] = malloc(2 * sizeof(char));     //MALLOC
names[1] = "1\0";


int i;
for (i = 0; i < icount; i++) {
    names[i + 2] = malloc(17 * sizeof(char));    //MALLOC
    fscanf(file, "%*[: ]%16s", names[i + 2]);
}


names = realloc(names, size * sizeof(char *));   //REALLOC
for (i = 0; i < ocount; i++) {
    names[i + icount + 2] = malloc(17 * sizeof(char));   //MALLOC
    fscanf(file, "%*[: ]%16s", names[i + icount + 2]);
}


for (i = 0; i < numOutputs; i++) {
        fscanf(file, "%*[: ]%16s", v);
        int idx = indexOf(size, names, v);
        if (idx == -1) {
            size++;
            tcount++;
            names = realloc(names, size * sizeof(char *));    //REALLOC
            names[size - 1] = malloc(17 * sizeof(char));      //MALLOC
            strcpy(names[size - 1], v);
            step.outputs[i] = size - 1;
        }


        if (!steps) {
        steps = malloc(sizeof(struct directive));    //MALLOC
    } else {
        steps = realloc(steps, scount * sizeof(struct directive));     //REALLOC
    }

You have a memory leak here:您在这里有 memory 泄漏:

names[0] = malloc(2 * sizeof(char));     //MALLOC
names[0] = "0\0";
names[1] = malloc(2 * sizeof(char));     //MALLOC
names[1] = "1\0";

You allocate space and assign a pointer to that space to names[0] , then you immediately overwrite the pointer to the allocated space with a pointer to a string constant.您分配空间并将指向该空间的指针分配给names[0] ,然后立即用指向字符串常量的指针覆盖指向已分配空间的指针。 names[1] has the same problem. names[1]有同样的问题。

Use strcpy instead to copy the string into the allocated memory:改用strcpy将字符串复制到分配的 memory 中:

names[0] = malloc(2 * sizeof(char));     //MALLOC
strcpy(names[0], "0");
names[1] = malloc(2 * sizeof(char));     //MALLOC
strcpy(names[1], "1");

Note also that string constants are implicitly null terminated, so there's no need to add it manually.另请注意,字符串常量隐含 null 终止,因此无需手动添加。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM