ccalloc

Calloc memory being initialized to 0


I have a basic understanding of calloc(). It initializes the memory to 0, so why does this code:

table_t *table = calloc(1, sizeof(table_t));
printf("%d", *table);

I would expect this code to print 0, since I haven't put anything in that memory (I think); why does it give this error?

dictionary.c: In function ‘create_table’:
dictionary.c:11:14: error: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘table_t’ [-Werror=format=]
   11 |     printf("%d", *table);
      |             ~^   ~~~~~~
      |              |   |
      |              int table_t
cc1: all warnings being treated as errors

Does it make the memory 0 only for int*?


Solution

  • As the error message states, the %d format specifier is expecting an int as an argument, but you're passing it a table_t instead. Using the wrong format specifier triggers undefined behavior in your code. It doesn't matter how the memory was initialized.

    If you want to see what the memory looks like, you need to use an unsigned char * to iterate through the bytes and print that.

    table_t *table = calloc(1, sizeof(table_t));
    for (int i=0; i<sizeof(table_t); i++) {
        unsigned char *p = (unsigned char *)table;
        printf("%d ", p[i]);
    }
    printf("\n");