Why does my code produce more alloc'd memory than I asked for?

83 Views Asked by At
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);
}

When I run using Valgrind, I expect 2 allocs, 0 frees, however:

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)

Anyone have any idea where the extra alloc and free is coming from? I'm using Valgrind 3.18.1

I've tried running with --leak-check=full and various other options, but nothing is clarifying this, and ChatGPT is just a dumb program, so please don't recommend that thing, nor Phind.

1

There are 1 best solutions below

2
chqrlie On

The third allocation may have been performed by printf or during the C runtime initialization to allocate the buffer for the standard streams.

You can free those by closing the standard streams prior to leaving the main function with:

    fclose(stdin);
    fclose(stdout);