如何释放此strdup?

问题描述

我正在使用strdup复制命令中的值。我还在循环结束时释放了它,以确保没有任何泄漏,但是valgrind似乎不同意我的说法,并说此strdup分配的内容正在泄漏。有什么想法吗?

这是我的代码

int main(void)
{
init_ui();
hist_init(100);

char *command;
while (true) {
    signal(SIGINT,SIG_IGN);
    command = read_command();
    if (command == NULL) {
        break;
    }
    char *copy = strdup(command);
    char *args[4096];
    int tokens = 0;
    char *next_tok = command;
    char *curr_tok;
    while((curr_tok = next_token(&next_tok," \t\n\r")) != NULL) {
        if(strncmp(curr_tok,"#",1) == 0){
            break;
        }
        args[tokens++] = curr_tok;
    }
    args[tokens] = NULL;

    if(args[0] == NULL) {
        continue;
    }
     
    hist_add(copy);
    int builtin_status = handle_builtins(tokens,args);
    if(builtin_status == 0) {
        continue;
    }

    pid_t child = fork();
    if(child == -1){
        perror("fork");
    }
    else if(child == 0){
        int ret = execvp(args[0],args);
        if(ret == -1) {
            perror("execvp");
        }
        close(fileno(stdin));
        close(fileno(stdout));
        close(fileno(stderr));
        exit(EXIT_FAILURE);
    }
    else {
        int status;
        waitpid(child,&status,0);
        set_last_status(status);
    }
hist_destroy();
free(copy);
}
return 0;
}

这是valgrind给我的东西,我真的是想了解什么是错的,因为似乎释放了此strdup所定义的内容

HEAP SUMMARY:
==359074== in use at exit: 18 bytes in 2 blocks
==359074== total heap usage: 72 allocs,70 frees,20,000 bytes allocated
==359074==
==359074== 18 bytes in 2 blocks are definitely lost in loss record 1 of 1
==359074== at 0x483977F: malloc (vg_replace_malloc.c:307)
==359074== by 0x4A7D23E: strdup (in /usr/lib/libc-2.31.so)
==359074== by 0x10A703: main (shell.c:85)
==359074==
==359074== LEAK SUMMARY:
==359074== definitely lost: 18 bytes in 2 blocks
==359074== indirectly lost: 0 bytes in 0 blocks
==359074== possibly lost: 0 bytes in 0 blocks
==359074== still reachable: 0 bytes in 0 blocks
==359074== suppressed: 0 bytes in 0 blocks

解决方法

strdup()使用malloc()分配内存,因此为了重用strdup(),必须释放copy

如上文UnholySheep所述,continue导致忽略free()语句。解决此问题的一种方法是在每个free()之前放置一个额外的continue语句。