Calloc memory being initialized to 0

115 Views Asked by At

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*?

2

There are 2 best solutions below

1
dbush On BEST ANSWER

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");
4
David Jones On

The memory pointed at by table will contain zeroes but printf format specifiers are typed.

%d expects an int not a table_t (presuming that doesn't resolve to some type of int).

It's not clear what the code is expected to do. If the struct's first member is int i then you probably want this instead:

printf("%d", table->i)