Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I trust (uintptr_t)NULL to be equal to zero?

Tags:

c

null

pointers

I know that NULL is not required to be an all bits zero pattern. But I do wonder if

uintptr_t x = (uintptr_t)NULL;
printf("%" PRIuPTR, x);

is guaranteed to print 0? I suspect it's not, but just want to be sure.

Or more to the point. Can I trust this?

if( ((uintptr_t)f(x) | (uintptr_t)f(y)) != 0)

Assume f is a function returning a pointer. I suspect that this piece of code heavily relies on that NULL is an all bit zero pattern. Am I correct?

I know it's considered bad practice, and I would never write something like that myself, but I wonder if it's well defined.

I stumbled upon this piece of code in this answer where the author is using

while ( ( (uintptr_t)fgets(a,100,fp1) | (uintptr_t)fgets (b,100,fp) ) != 0 ) {
        printf("%s",a);
        printf("%s",b);
}
like image 919
klutt Avatar asked Oct 13 '25 00:10

klutt


1 Answers

In theory: no.

In practice: probably.

In the relevant standardese, the checks for null pointers are "special" in the sense that they are not numeric comparisons with the value zero, so in theory, some implementation or platform could assign a different value to null pointers.

like image 93
rubenvb Avatar answered Oct 14 '25 17:10

rubenvb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!