gpt4 book ai didi

c - free() 函数不释放堆内存

转载 作者:太空宇宙 更新时间:2023-11-04 06:48:06 27 4
gpt4 key购买 nike

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

#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.h:

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

void free_duplicated_args(char **copy);

duplicate.c:

#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);
}

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

==10412== HEAP SUMMARY:
==10412== in use at exit: 1 bytes in 1 blocks
==10412== total heap usage: 3 allocs, 2 frees, 1,033 bytes allocated
==10412==
==10412== 1 bytes in 1 blocks are definitely lost in loss record 1 of 1
==10412== at 0x483577F: malloc (vg_replace_malloc.c:299)
==10412== by 0x10927C: duplicate_args (in /root/Documents/OS/proj2/project/proj2)
==10412== by 0x109194: main (in /root/Documents/OS/proj2/project/proj2)
==10412==
==10412== LEAK SUMMARY:
==10412== definitely lost: 1 bytes in 1 blocks
==10412== indirectly lost: 0 bytes in 0 blocks
==10412== possibly lost: 0 bytes in 0 blocks
==10412== still reachable: 0 bytes in 0 blocks
==10412== suppressed: 0 bytes in 0 blocks
==10412==
==10412== For counts of detected and suppressed errors, rerun with: -v
==10412== ERROR SUMMARY: 5 errors from 5 contexts (suppressed: 0 from 0)

最佳答案

您的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);
}

关于c - free() 函数不释放堆内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55303461/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com