If `malloc(0)` returns a non-null pointer, can I pass that to `free`?

Viewed 3200

I've been reading over discussions of how malloc behaves when you request a zero sized block.

I understand that the behavior of malloc(0) is implementation-defined, and it is supposed to either return a null pointer, or a non-null pointer that I am nonetheless not supposed to access. (Which makes sense, since there's no guarantee that it points to any usable memory.)

However, if a get such a nonaccessable non-null pointer, am I allowed to pass it to free in the usual way? Or is that illegal, since the pointer I get from malloc(0) may not point to an actual allocated block of memory?

Concretely, does the following code have well-defined behavior:

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

int main() {
    int* x = (int*) malloc(0);
    if (x == NULL) {
        printf("Got NULL\n");
        return 0;
    } else {
        printf("Got nonnull %p\n", x);
    }
    free(x); // is calling `free` here okay?
}
2 Answers
Related