r/C_Programming • • Sep 20 '26

Question A way to warn on NULL and 0 comparisons

Hi y’all. I’m rewriting a small library written by another person, and there are lots of pointer and integer comparisons there. However, these are not caught by the compiler (tried both GCC and Clang,) because they are mostly comparisons between NULL and 0. Comparing NULL to any other integer throws warnings, but not for 0. Is there a way I can force warnings even for such case? Tried these GCC and Clang flags, to no avail:

  • -Wpointer-arith
  • -Waddress
  • -Wint-to-pointer-cast
  • -Wpointer-to-int-cast
  • -Wincompatible-pointer-types
  • -Wint-conversion

Also tried using C23 nullptr—nope, does not warn.

So, any way I can outlaw NULL==0 comparisons?

Update: it’s -Wzero-as-null-pointer-constant on GCC 15+ or G++, thanks to u/skeeto and u/WittyStick for mentioning it.

27 Upvotes

61 comments sorted by

26

u/zhivago Sep 20 '26

NULL is defined as an integer expression equal to 0, or such converted to void *.

So (void *)(20 / 2 -5) is valid, as is (23 - 23).

There is a defined conversion from a constant zero void * expression to 0 as an integer.

So, no -- you cannot prevent this comparison in C.

It's baked into the language.

You could try writing a new language which differs on this point, I guess, but it wouldn't be C.

4

u/aartaka Sep 20 '26

That’s a bummer, but thank you!

3

u/realhumanuser16234 Sep 20 '26

there are warnings for things that are valid c code

4

u/Plus-Dust Sep 20 '26

True..I'm not sure how exactly it would work, but maybe something could be done with #undefing NULL and redefining it to something else? I mean, obviously the program wouldn't work any more, but might could be made to generate errors on compile.

0

u/flyingron Sep 20 '26 edited Sep 21 '26

Integer CONSTANT expression. Not any integer.

7

u/WittyStick Sep 20 '26

-Wzero-as-null-pointer-constant

2

u/aartaka Sep 20 '26

Gods bless you.

1

u/RealisticDuck1957 Sep 24 '26

From man gcc

-Wzero-as-null-pointer-constant (C++ and Objective-C++ only)

Warn when a literal 0 is used as null pointer constant. This can

be useful to facilitate the conversion to "nullptr" in C++11.

4

u/skeeto Sep 20 '26 edited Sep 20 '26

GCC 15 has -Wzero-as-null-pointer-constant, which solves just this problem. If you're stuck with an older GCC, and if the program can parse as C++ then you can use GCC's C++ front end. For example:

int f(char *x)
{
    return x == 0;
}

Then:

$ gcc -xc++ -fsyntax-only -Wzero-as-null-pointer-constant example.c
example.c: In function ‘int f(char*)’:
example.c:3:17: warning: zero as null pointer constant [-Wzero-as-null-pointer-constant]
    3 |     return x == 0;
      |                 ^

For Clang you can use clang-query, which doesn't require C++:

$ clang-query -c 'm implicitCastExpr(
    hasCastKind("CK_NullToPointer"),
    has(integerLiteral(equals(0))),
    unless(isExpandedFromMacro("NULL")),
    isExpansionInMainFile())' example.c -- -std=c23 

Match #1:

example.c:3:17: note: "root" binds here
    3 |     return x == 0;
      |                 ^
1 match.

3

u/aartaka Sep 20 '26

I’m on GCC 14 rn, but I ran things through g++ 14 with -Wzero-as-null-pointer-constant, and it did highlight the problematic casts! Thanks for the suggestion!

29

u/CounterSilly3999 Sep 20 '26

Null pointer is an architecture dependent feature and not allways internally represented as a value of all bits set to zero. Hence C has a requirement for the integer value 0 to be cast to null pointer at integer conversion to a pointer and back. It is the only way to recognize null pointer -- compare it to integer zero.

7

u/Dangerous_Region1682 Sep 20 '26

Yes, and historically there have been a few systems where this is the case, NULL is not all bits set to zero. But any comparison of NULL to zero must return true. The compiler has to correctly cast from integers, unsigned or not, to pointers and back.

It is helpful if the value for NULL in a pointer results in a segmentation fault or access violation by the virtual memory page it is being mapped to is undefined. With accessing NULL pointer dereferenced being undefined, I suspect it actually doesn’t have to be so, and sometimes hasn’t been. UNIX V6 if I remember correctly on a PDP-11 it depended upon the a.out type and whether the specific PDP-11 supported split I and D binaries. If you compiled for such, the data segment started at 000 so writing to a NULL pointer didn’t cause an exception. You had to compile to different a.out formats to check for such errors. It’s been a while, like 45+ years, but this is what I remember.

Some machines, such as Multics, early CDC Cyber series and some Honeywell Bull mainframe systems didn’t use all bits set to zero for NULL. Of course the C compiler had to cope with this, but it was down to the user not to try to circumvent the compiler from handling this. Back in those days compilers were easily fooled.

Today of course most systems use all zero bits to represent NULL and the first page of the data segment doesn’t map the virtual memory to physical memory. This results in the lowest valid virtual address for memory depends upon the page size. You cannot assume because 0x0 is not valid that 0x1 is.

1

u/CounterSilly3999 Sep 20 '26

If I remember correctly, PDP-11 didn't have an explicit null-pointer concept (nor Intels do?). Zero was a valid addres, while mapped to a real memory page. I wonder, what was a special behavior and usecases for null pointer, where it was implemented. Trapped it to some special interrupt vector in contrast to ordinary seg fault? Was it used may be to initialize the memory?

7

u/aioeu Sep 20 '26 edited Sep 20 '26

nor Intels do?

That's right. The zero address is perfectly usable on x86, both as a physical address and a virtual address.

(Linux happens to not use the first page of physical memory on x86, but that's not a hardware limitation. I'm pretty sure it's just so that page frame number 0 can be used as a convenient sentinel value where it makes sense to do so. Linux is also often configured so that a certain range of low virtual addresses cannot be mapped in a process, but again that's not a hardware limitation. I would not be surprised if other OSs do similar things.)

3

u/smcameron Sep 20 '26

DOS used to put the interrupt vector table starting at address 0, iirc.

1

u/RealisticDuck1957 Sep 24 '26

Which is a matter of the hardware, 8086 or compatible mode on later processors.

1

u/Dangerous_Region1682 Sep 20 '26

Well it depended upon which PDP-11 you compiled for. On a PDP-11/45 if you compiled for separate instruction and data spaces, 0x0 (I probably should use octal here) was a valid instruction and data space value, at least on UNIX V6. Earlier architecture PDP-11s like the 11/40 didn’t support such binaries. If you moved code you built from an 11/40 to an 11/45 you had to recompile it to take advantage of the split I&D space.

So you traded the advantages of split I&D space for the inability to trap accessing the data with NULL pointers at runtime.

Well to be accurate, the target memory layout chosen in the binary was a function of the linker, ld(1), not the compiler cc(1) per se. If I remember correctly it was a “-i” parameter, but now that’s really resting my memory. This was for user space programs, I can’t remember how we built code for kernel space to be honest.

1

u/flatfinger Sep 21 '26

The only things necessary to make all-bits zero be usable as the null pointer address are that neither the compiler nor linker ever place named objects there, and allocations returned by malloc() never include that address, even on platforms where pointers are treated as signed.

1

u/RealisticDuck1957 Sep 24 '26

Which works for any address that the necessary software recognizes as reserved for the purpose.

1

u/Intelligent_Law_5614 Sep 20 '26

On the Honeywell hardware I worked on, pointers contained both a descriptor number (in the LSBs) and a byte offset. If I recall correctly, the 06000 range of descriptor numbers were used for user-mode memory segments, and on the OS I worked with (CP-6) descriptor 06014 was mapped to an empty, unallocated segment. So, NULL in C was represented as (0,06014) but had to compare equal to zero (and zero had to transmogrify into (0,06014) during a cast to any pointer type).

On this hardware, 0 was a legitimate address pointer and in fact was quite commonly used (iirc, on entry to the kernel via a syscall it pointed to the first parameter block passed in the call from user space) and hence the conventional value of 0 could not be used as a NULL.

This all caused the Waterloo C team some amount of indigestion, I recall.

-2

u/zhivago Sep 20 '26

You're confusing NULL with the null pointer value.

3

u/CounterSilly3999 Sep 20 '26

Where? I thought the contrary -- separating. If you would care about the internal value of the null pointer, you will have architecture dependent code. Assuming int 0 casts to null pointer results in resolving the issue. Comparing a pointer with integer 0 involves implicit cast.

2

u/Dangerous_Region1682 Sep 20 '26

The OP said he was talking about NULL and 0s in integer pointer values.

→ More replies (8)

1

u/Total-Box-5169 Sep 20 '26

That feature is only necessary to initialize pointers to the null-pointer value. Even in ANSI C null-pointer value evaluates to false and non null-pointer evaluates to true, so no comparisons against zero are necessary.

2

u/CounterSilly3999 Sep 20 '26

C had no boolean type initially. if(ptr) was comparison against integer zero actually.

1

u/RealisticDuck1957 Sep 24 '26

When null is defined in a standard header why does there need to be a specific integer conversion? Other than the mass of code out there (including in the linux kernel last I looked) that assumed null == 0.

11

u/hikilaka Sep 20 '26

Null is defined as 0, is it not?

19

u/Mr_Engineering Sep 20 '26

NULL is an implementation defined constant

It is either a void pointer with a value of zero, an integer with a value of zero, or a long with a value of zero.

3

u/Jbolt3737 Sep 20 '26 edited Sep 20 '26

I always assumed that it was implementation specific because sometimes a null pointer won't actually be represented with 0 on some systems or something (now questioning if that's actually true), is it really that convoluted for it to just be 0?

Edit: I'm still a bit of a beginner in C, and I am realizing that perhaps if there are weird architectures where a null pointer isn't all 0 bits, it's reasonable to assume there might be architecture where the size of a pointer might not be 32 or 64 bits, in which case all of this makes more sense

11

u/aioeu Sep 20 '26 edited Sep 20 '26

Even if a null pointer is represented with an object that doesn't consist only of zero bits, it must compare equal to 0 — and thus will be false when tested for truthiness, e.g. by if — and 0 must be able to be used as a null pointer constant.

Note that that doesn't mean 0 itself is a null pointer; it is still an int. A null pointer constant can be, but does not need to be, a pointer. Indeed, the fact that null pointer constants are a distinct concept from null pointers is precisely how the compiler on this kind of system can deal with null pointers not being all-zero-bits objects, even if zero integers are. It knows which expressions have pointer type and which do not.

There have been some oddball architectures in the past where null pointers were not all-zero-bits, but it might be hard to find one now.

3

u/zhivago Sep 20 '26

NULL is not a null pointer value, which is probably what is confusing you.

The null pointer value can be whatever it likes.

0

u/Mr_Engineering Sep 20 '26

Nope. NULL must be zero according to the standard, but it is up to the C implementation to determine the underlying type used for the constant.

744 An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant

and

758 The macro NULL is defined in <stddef.h> (and other headers) as a null pointer constant; see 7.17.

So, any standard conformant C compiler must have NULL be defined as either an integral 0 or a void pointer with a value of 0

C allows implicit conversion of void pointers to pointers other types so any pointer can be compared to (void*)0 without casting because C explicitly allows that.

Now, in C++, implicit conversion between pointer types is disallowed due to strong typing. This means that an integer pointer cannot be compared to a void pointer without explicit casting, so defining NULL as a void pointer with a value of zero is disallowed. Instead, C++ defines NULL as either 0, 0L, or the newish nullptr. C++ explicitly allows comparison between pointers and integral 0

If you take a look at stddef.h (which is also cstddef by way of symlink) for glibc on most Linux systems you'll find a set of precompiler macros which define NULL differently depending on whether it's being used for Golang, C, or C++; ditto for libc on FreeBSD and MacOS. I'm not sure how MSVC defines it and I'm not going to look right now.

0

u/flyingron Sep 21 '26

No. It's got to be the null pointer constant (a constant integer expression evaluating to zero) or that value cast to void*. It can't be any random other integer or void* value.

0

u/Mr_Engineering Sep 21 '26

Your reading comprehension needs work

→ More replies (5)

7

u/meancoot Sep 20 '26

In C it is an an implementation-defined null pointer constant, historically (void*)0. In C++ it is typically just 0, and C++ requires that 0 be implicitly convertible to a null pointer.

Check https://github.com/gcc-mirror/gcc/blob/master/gcc/ginclude/stddef.h starting at line 418 for how glibc defines it.

0

u/Vladislav20007 Sep 20 '26

gnu's libc's implementation is (void*)0 and just 0, if it's cpp.

2

u/qalmakka Sep 21 '26 edited Sep 21 '26

Comparing a pointer with zero is perfectly legal, because while the standard doesn't define what null actually is, it defines that the zero literal converts to it implicitly. i.e. you may have a strange architecture where pointers are structs and null is a non-zero pattern, and still void *x = 0 will end up with xcontaining the value of null.

For instance, in C99 #define NULL ((void*)0) is always legal and portable

0

u/BarracudaDefiant4702 Sep 20 '26

In C NULL is 0 and is part of the standard. Even if NULL isn't 0 it's defined that the compiler has to treat a comparison to 0 as NULL. Why would you want to outlaw NULL==0 comparisons (NULL==0 is always true)? Perhaps give a code example where you think the compiler should complain (like a pointer to int comparison), but comparing to 0 is explicitly part of the standard.

2

u/aartaka Sep 20 '26

Well, I have arrays of strings interspersed with 0-s, and I want to convert them all to valid pointers (NULL in case there’s no string.) I realize that NULL==0, but I want to have them consistent in types, with no integers where pointers should be.

0

u/questron64 Sep 20 '26

What exactly are you trying to achieve here? As others have pointed out NULL, nullptr and 0 are all more or less the same thing, and a feature of the language is that NULL is equal to 0 for any test of equality and because of that there is no warning, and there doesn't need to be a warning.

This is something a code audit and come typing will fix.

1

u/aartaka Sep 20 '26

I want my data to consistently be pointers and not pointers+zeros. I realize this is at this point a matter of aesthetics and not pragmatics, but I want it anyway.

1

u/sciencekm Sep 20 '26

Zero is correct and NULL is just for clarity. Here is what the K&R book says:

The symbolic constant NULL is often used in place of zero, as a mnemonic to indicate more clearly that this is a special value for a pointer.

0

u/cnbatch Sep 20 '26

How about giving C11’s _Generic a try, together with C23’s nullptr:

https://godbolt.org/z/415xYax3d

1

u/aartaka Sep 20 '26

nullptr_t is not supported on many compilers, and nullptr still casts to 0 on comparison, apparently.

1

u/cnbatch Sep 20 '26

Here are two versions for your reference:

Version 1, comparing the input parameter with `null` causes the compiler to throw errors:

https://godbolt.org/z/WG4zj6h3E

Version 2, comparing the input parameter with `NULL` results in a compiler warning rather than an error:

https://godbolt.org/z/f9xsxacbz

2

u/aartaka Sep 20 '26

Version 2 is more interesting to me, because, it seems, the compiler stops detecting that 0 is a literal integer coercible to NULL.

And I think that Version 1 is irrelevant, because it works with a different (and easier) problem: how do we detect when we are passed a pointer into an integer function? This is solveable, as your output shows.

My problem is exact opposite: passing an integer 0 to a pointer function or pointer comparison. Like many in this thread have mentioned, 0 is automatically converted to NULL whenever necessary, so there’s no easy pre-C11/C23 way to detect when we erroneously compare a pointer with a 0. We need a compiler flag for that, and -Wzero-as-null-pointer-constant is the one.

0

u/flyingron Sep 20 '26

Comparing pointers to the integer-pointer-constant (e.g., 0) is perfectly valid.