我是编程新手,目前正在尝试编写一个可以使用多线程模拟 du 命令的程序。我的程序运行良好,但我遇到了一些内存泄漏,我不太确定如何修复。
这是我遇到问题的功能:
void addSubdirectories(const char *basePath) {
linkedlist *stack = linkedlist_empty();
if (stack == NULL) {
return; // Exit function if memory allocation fails
}
searching((char *)basePath, &dir_lock);
linkedlist_insert(linkedlist_first(stack), strdup(basePath)); // Insert base path into the list
while (!linkedlist_isEmpty(stack)) {
char *currentDir = strdup(linkedlist_inspect(linkedlist_first(stack)));
if (currentDir == NULL) {
break; // Exit loop if memory allocation fails
}
linkedlist_remove(linkedlist_first(stack));
DIR *dir = opendir(currentDir);
if (dir == NULL) {
free(currentDir);
continue;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_DIR) {
if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {
char subDirPath[MAX_PATH_LENGTH];
snprintf(subDirPath, sizeof(subDirPath), "%s/%s", currentDir, entry->d_name);
// Add subdirectory to the list for traversal
searching(subDirPath, &dir_lock);
linkedlist_insert(linkedlist_first(stack), strdup(subDirPath)); // Insert subdirectory into the stack
}
}
}
closedir(dir);
free(currentDir); // Free memory for currentDir after removing from the list
}
linkedlist_free(stack);
}
我一直在使用 valgrind 所以我知道泄漏在哪里,但我所有释放内存的尝试都失败了
10,982 bytes in 500 blocks are definitely lost in loss record 10 of 10
at 0x48407B4: malloc (vg_replace_malloc.c:381)
by 0x49227F9: strdup (strdup.c:42)
by 0x10A25B: addSubdirectories (mdu.c:329)
by 0x109734: main (mdu.c:28)
我觉得我明显缺少一些东西,有人可以帮助我吗,任何帮助将不胜感激!
编辑:这是我用来分配空间的链表https://pastebin.com/Qz3zF7A7
linkedList_insert()
有自己的调用 strdup()
:
newNode->value = strdup((char*)v); // Using strdup to duplicate the string
所以调用的时候不需要调用
strdup()
。由于您从未释放自己的重复项,因此它们会导致内存泄漏。