在 C 中使用 getline 从 stdin 读取时如何避免内存泄漏?

发布于 2023-02-13 08:42:17

我在使用 getline 从 C 中的标准输入读取时遇到内存泄漏,尽管确保释放了所有 malloc,但在构建一个简单的 shell 时问题仍然存在。作为 C 的新手,我正在寻找有关在使用 getline 进行文件输入时如何正确处理内存的建议。

这是我用来阅读该行的代码

char *readline(int *eof)
{
    char *input = NULL;
    size_t bufsize = 0;
    *eof = getline(&input, &bufsize, stdin);
    return (input);
}

这是实际的主要功能。


    while (status)
    {
        mode = isatty(STDIN_FILENO);
        if (mode != 0)
        {
            write(STDOUT_FILENO, "$ ", 3);
        }
        line = readline(&eof);
        if (eof == -1)
        {
            exit(EXIT_FAILURE);
        }
        args = tokenize(line);
        status = hsh_execute(args, env, argv[0]);
        i = 0;
        while(args[i] != NULL)
        {
            free(args[i]);
            i++;
        }
        free(args);
        free(line);
    }

这是我运行命令 echo "/bin/ls" | 时 valgrind 返回的错误。 。/壳

==33899== Invalid free() / delete / delete[] / realloc()
==33899==    at 0x484B27F: free (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
==33899==    by 0x10980D: main (shell.c:40)
==33899==  Address 0x4a96040 is 0 bytes inside a block of size 120 free'd
==33899==    at 0x484B27F: free (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
==33899==    by 0x1097D5: main (shell.c:36)
==33899==  Block was alloc'd at
==33899==    at 0x4848899: malloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
==33899==    by 0x48EB1A2: getdelim (iogetdelim.c:62)
==33899==    by 0x1096CA: readline (readline.c:12)
==33899==    by 0x10976B: main (shell.c:26)
==33899== 
==33899== 
==33899== HEAP SUMMARY:
==33899==     in use at exit: 120 bytes in 1 blocks
==33899==   total heap usage: 4 allocs, 4 frees, 4,848 bytes allocated
==33899== 
==33899== LEAK SUMMARY:
==33899==    definitely lost: 0 bytes in 0 blocks
==33899==    indirectly lost: 0 bytes in 0 blocks
==33899==      possibly lost: 0 bytes in 0 blocks
==33899==    still reachable: 120 bytes in 1 blocks
==33899==         suppressed: 0 bytes in 0 blocks
==33899== Rerun with --leak-check=full to see details of leaked memory
==33899== 
==33899== For lists of detected and suppressed errors, rerun with: -s
==33899== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

查看更多

1楼回答 2023-02-03

我猜这条线

char *readline(int *eof)

应该

char *readline(size_t *eof)

并且 eof 应该相应地声明。

请登录后再发布答案,点击登录