Search code examples
clanguage-lawyerundefined-behaviorcalloc

Can all bits 0 be a trap representation for integers?


It is common to assume that initializing an object to all bits 0 is a simple way to set all its members to 0. The standard does not guarantee this for non integer types as:

  • all bits zero might not be a valid representation for pointers, even null pointers, although all common modern systems use exactly that.
  • all bits zero might not be a legal representation for floating point numbers, although it is on IEEE compliant systems.

What about integers? Is the following code fully defined:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    int *p = calloc(sizeof(*p), 1);
    if (p) {
        printf("%d\n", *p);
        memset(p, 0, sizeof(*p));
        printf("%d\n", *p);
        free(p);
    }
    return 0;
}

Solution

  • From C Standard, 6.2.6.2, Integer Types

    For any integer type, the object representation where all the bits are zero shall be a representation of the value zero in that type.