free()函数不会释放堆内存

时间:2019-03-22 15:55:44

标签: c malloc free

我有3个文件proj2.c,duplicate.h,duplicate.c proj2.c:

function ContextMenuItems({ children }): JSX.Element | null {
   if (!React.Children.count(children)) return null;
   ...
}

duplicate.h:

#include <stdio.h>
#include "duplicate.h"
#include<stdlib.h>
int main(int argc, char **argv)
{
    if (argc <= 1)
    {
        return 1;
    }

    char **copy = duplicate_args(argc, argv);
    char **p = copy;
    argv++;
    p++;

    while (*argv)
    {
        //printf("%s %s\n", argv[1], copy[1]);
        printf("%s %s\n", *argv++, *p++);
    }

    free_duplicated_args(copy);
    //free(copy);
    return 0;
}

duplicate.c:

char **duplicate_args(int argc, char **argv);

void free_duplicated_args(char **copy);

程序非常简单。接受n个参数并更改字符串的大写形式。我正在创建一个新数组来存储argv的副本(使用malloc)。现在,当我运行valgrind时:valgrind --leak-check = full ./proj2 1 它说丢失了1个字节。

#include<stdlib.h>
#include<string.h>
#include<stdio.h>
char **duplicate_args(int argc, char **argv)
{
        char **arrPointer=malloc((argc-1)*sizeof(char*));
        for(int i=1;i<argc;i++)
        {
                arrPointer[i] = (char*)malloc(strlen(argv[i])*sizeof(char));
                for(int j=0;j<strlen(argv[i]);j++)
                {
                        if(argv[i][j] > 64 && argv[i][j] < 91)
                        {
                                arrPointer[i][j]=argv[i][j]+32;
                        }
                        else if(argv[i][j] > 96 && argv[i][j] < 123)
                        {
                                arrPointer[i][j]=argv[i][j]-32;
                        }
                        else
                        {
                                arrPointer[i][j]=argv[i][j];
                        }
                }
//              arrPointer[i]=argv[i];

        }
        return arrPointer;
}

void free_duplicated_args(char **copy)
{
        free(copy);
}

1 个答案:

答案 0 :(得分:3)

您的duplicate_args调用malloc argc次,而free_duplicated_args仅调用free一次,这就是内存泄漏的原因。应该是

void free_duplicated_args(int argc, char **copy)
{
    for (int i = 1; i < argc; i++)
        free (copy [i]);

    free(copy);
}