为什么我的代码产生的分配内存比我要求的多?

问题描述 投票:0回答:1
typedef struct hash_node_s
{
    char *key;
    char *value;
    struct hash_node_s *next;
} hash_node_t;

typedef struct hash_table_s
{
    unsigned long int size;
    hash_node_t **array;
} hash_table_t;

hash_table_t *hash_table_create(unsigned long int size)
{
    hash_table_t *table;

    table = malloc(sizeof(hash_table_t));

    if (!table)
    {
        printf("failed to create table");
        return (NULL);
    }

    table->size = size;
    table->array = malloc(sizeof(hash_node_t *) * size);

    if (!table->array)
    {
        printf("failed to create table->array");
        free(table);
        return (NULL);
    }

    return (table);
}

int main(void)
{
    hash_table_t *ht;

    ht = hash_table_create(1024);
    printf("%p\n", (void *)ht);

    return (EXIT_SUCCESS);
}

当我使用 Valgrind 运行时,我期望 2 次分配,0 次释放,但是:

root@anon# valgrind ./a
==1374== Memcheck, a memory error detector
==1374== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==1374== Using Valgrind-3.18.1 and LibVEX; rerun with -h for copyright info
==1374== Command: ./a
==1374==
0x4a8c040
==1374==
==1374== HEAP SUMMARY:
==1374==     in use at exit: 8,208 bytes in 2 blocks
==1374==   total heap usage: 3 allocs, 1 frees, 9,232 bytes allocated
==1374==
==1374== LEAK SUMMARY:
==1374==    definitely lost: 16 bytes in 1 blocks
==1374==    indirectly lost: 8,192 bytes in 1 blocks
==1374==      possibly lost: 0 bytes in 0 blocks
==1374==    still reachable: 0 bytes in 0 blocks
==1374==         suppressed: 0 bytes in 0 blocks
==1374== Rerun with --leak-check=full to see details of leaked memory
==1374==
==1374== For lists of detected and suppressed errors, rerun with: -s
==1374== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

有人知道额外的分配和释放来自哪里吗?我正在使用 Valgrind 3.18.1

我尝试使用 --leak-check=full 和各种其他选项运行,但没有任何东西可以澄清这一点,ChatGPT 只是一个愚蠢的程序,所以请不要推荐那个东西,也不要推荐 Phind。

c memory malloc hashtable free
1个回答
0
投票

第三次分配可能由

printf
或在 C 运行时初始化期间执行,为标准流分配缓冲区。

您可以通过在离开

main
函数之前关闭标准流来释放这些流:

    fclose(stdin);
    fclose(stdout);
© www.soinside.com 2019 - 2024. All rights reserved.