if语句中的malloc(),仅当输入(if)但valgrind说字节丢失时才赋值

问题描述 投票:-3回答:2

在使用C进行分配的情况下,我必须创建li克隆,我正在尝试访问目录中所有子文件的名称。

带有变量:

directoryUtilities.h中:

#define THEORETICAL_MAX_PATH LENGTH 4096

directoryRunner.c中:

char *files[THEORETICAL_MAX_PATH_LENGTH];
//Later
int count = 0;
const char *path = "some/path"; //An actual path here
struct dirent *currentDir;
DIR *folder = opendir(path); // EDIT: was mistakenly retyped as readdir(...), is really opendir(...).

在以下由getChildren(...)调用的createNode(...)调用的main(...)内的函数中:

if (access(path, F_OK) != -1) {
    if (folder)
        while ((currentDir = readdir(folder))) {
            if (strcmp(currentDir->d_name, ".") && strcmp(currentDir->d_name, "..")) {
                files[count] = (char*) malloc(THEORETICAL_MAX_PATH_LENGTH); 
                snprintf(files[count], THEORETICAL_MAX_PATH_LENGTH, "%s", currentDir->d_name);
                    count++;
            }
        }
}
closedir(folder);

[如果解析文件的名称是...,我试图避免附加到文件,因为显然我正在尝试避免循环。

我的问题是valgrind打印出来:

==2175== HEAP SUMMARY:
==2175==     in use at exit: 12,288 bytes in 3 blocks
==2175==   total heap usage: 93 allocs, 90 frees, 419,154 bytes allocated
==2175==
==2175== 12,288 bytes in 3 blocks are definitely lost in loss record 1 of 1
==2175==    at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==2175==    by 0x109132: getChildren (directoryRunner.c:47)
==2175==    by 0x10931E: createNode (directoryRunner.c:95)
==2175==    by 0x109492: createNode (directoryRunner.c:114)
==2175==    by 0x109492: createNode (directoryRunner.c:114)
==2175==    by 0x109492: createNode (directoryRunner.c:114)
==2175==    by 0x109598: main (main.c:22)
==2175==
==2175== LEAK SUMMARY:
==2175==    definitely lost: 12,288 bytes in 3 blocks
==2175==    indirectly lost: 0 bytes in 0 blocks
==2175==      possibly lost: 0 bytes in 0 blocks
==2175==    still reachable: 0 bytes in 0 blocks
==2175==         suppressed: 0 bytes in 0 blocks

[directoryRunner.c:46是在其中调用files[count] = (char*) malloc(THEORETICAL_MAX_PATH_LENGTH);的行,并且没有在if语句中输入的情况。

这并不妨碍我的代码的功能,但是我想尽可能避免泄漏内存,并在此之后感谢您的任何帮助。

对于最小的可复制代码,因为无论如何,所有内容都是半互连的,here is the code

要进行复制,请确保已安装valgrind,并使用make(包括Makefile)进行编译。

make
valgrind --tool=memcheck --leak-check=yes --track-origins=yes --read-var-info=yes -v ./ultra_cp var 

编辑:免费的否决票是必要的吗?这个问题是真实的,结构合理的。我希望您只说您不知道。

c malloc valgrind
2个回答
2
投票

如果您有条件地分配内存,则还必须将其设置为free。直观地,人们可能会认为他们需要在尝试释放内存之前检查是否已分配内存,但是幸运的是,C标准已经涵盖了我们。

您可以通过在循环外(或在NULL语句中)将文件指针设置为else,然后在代码中稍后调用free()来捷径一些代码,一旦您知道您不会不再使用内存了。您不需要检查指针是否已分配,因为free(NULL) is a perfectly legal no-op.


0
投票

嗯,这无济于事。关于释放内存的所有建议都是先前实现的,即使在其他地方也是如此。在条件语句中分配内存显然很困难(与我的一位单教授交谈),因此考虑到它不会影响最终性能,我将忽略valgrinds输出。

我也会关闭Git。

仍然感谢。

© www.soinside.com 2019 - 2024. All rights reserved.