1

i am working on a homework and since our constraints are really strict i need to check for NULL pointers everywhere if i want 100%. So i made a little inlined function which checks pointers for NULL:

static inline void exit_on_null(void* ptr, const char* msg) {
    if ( ! ptr ) {
        printf("%s\n", msg);
        exit(1);
    }
}

Now i asked myself is it safe to do so? From the standard i know it is save to cast a pointer to void* and back and receive the original pointer. Does that give that the void* version of the pointer is still comparable to NULL or is there some pitfall i can run in? For example is the following always true?

ptr = NULL
(void*) ptr == NULL
Yastanub
  • 1,227
  • 8
  • 19

2 Answers2

2

I found the answer myself in the standard:

6.3.2.3 Pointers

4 Conversion of a null pointer to another pointer type yields a null pointer of that type. Any two null pointers shall compare equal.

Community
  • 1
  • 1
Yastanub
  • 1,227
  • 8
  • 19
  • That is not quite the answer for the `!ptr` test. `!ptr` is not a comparison. Per C 2018 6.5.3.3, it is essentially equivalent to `ptr == 0`, which compares a pointer to an `int` with value zero. This qualifies as a *null pointer constant* per 6.3.2.3 3, which satisfies the constraints for `==`. Then 6.3.2.3 5 tells us the `0` is converted to the type of `ptr`. 6.3.2.3 3 tells us converting a null pointer constant to a pointer produces a null pointer. Then 6.5.9 6 tells us the comparison is true if `ptr` is null and false otherwise. – Eric Postpischil Jun 09 '19 at 01:30
  • And that's why many coding rules require to use "correct" boolean expressions, in this case `if (ptr == NULL)`. ;-) – the busybee Jun 09 '19 at 09:07
0

How do you think that's not safe? But don't do this

static inline void exit_on_null(void* ptr, const char* msg) {
    if (!*(void **)ptr) {
        printf("%s\n", msg);
        exit(1);
    }
}
// segfault
exit_on_null(NULL, "yeet");
oakaigh
  • 46
  • 2
  • 5