125 points · by mikece · 3y ago · 101 comments
If you ever see the macro NULL in code, be afraid. There are two valid ways of defining the macro and that cause weird issues when porting code. For example, in the statement printf ("%p %s\n", NULL, "Hello world!"), one of the definitions leads to NULL being interpreted as the null pointer, and the other leads to NULL being interpreted as an integer. The latter may crash if integer and pointer are different sizes.
It also causes problems with C++ overloading if one overload takes a pointer and another takes an integer.
Not on a Posix system, where the only valid definition of it is `(void*)0`. C could have adopted this definition.
Nullptr is needed in C++ because `0` is the only definition of `NULL` that works with the type system, due to the lack of implicit `void*` conversions.
C doesn't have this problem.
Adopting the Posix definition of NULL in the standard would have been sufficient -- and unlike `nullptr`, would have solved bugs in existing programs.
> C doesn't have this problem.
Except for conversions between data pointers and function pointers ;)
Initialization seems to be a special case, but with `-pedantic` the following code will show a warning on the initialization of `fp2`:
void* return_null() {
return 0;
}
int main() {
void(*fp1)() = 0;
void(*fp2)() = return_null();
return 0;
}I don't think a strong type system is a `problem`, implicit conversions can lead to so many annoying and hard to find bugs.
char *x = 0; // ok in C and C++
char *y = (void*)0; // ok in C, error in C++
char *z = nullptr; // ok in C++
therefore: #define NULL ((void*)0) // Required by Posix C, invalid C++
#define NULL 0 // Pre-nullptr, the only valid C++ definition
C++ can't define NULL the safe way that Posix C does.I don't understand why it's more acceptable to allow magic `0` conversions than magic `(void*)0` conversions, given that the latter is far less likely to happen by accident -- but here we are.
implicit void
conversions are the problem- NULL is idiomatic: using NULL is entrenched in C programming and it is not going away.
- In spite of nullptr existing now, NULL is still (quite stupidly) not required to just expand to nullptr, but to an implementation-defined null pointer constant, rather than #define NULL nullptr. (According to the N2596 draft).
- They had over 30 years to tighten the requirements on how NULL can be defined; what's the matter? C99 could already have required NULL to be ((void *) X) where X is an integer-typed constant expression evaluating to zero.
I'm not going to start using nullptr. It's not idiomatic C. I'm going to hold out hope that NULL will be fixed so that it expands to nullptr.
--
Also, it's possible for a compiler to diagnose when a constant, zero-valued expression is used as the argument of a variadic function. The diagnostic can be confined to cases when such a constant expression is the result of macro expansion:
printf_like_function("fmt ...", ... 0, ...); // OK
#define FOO 0
printf_like_function("fmt ...", ... FOO, ...); // compiler diagnostic
printf_like_function("fmt ...", ... (int) FOO, ...); // OKThis is so silly. I sort of get why not (can't break the dork that decided to do
int i = NULL;
i++;
)But, at the same time... I almost feel like this is a "you are being a dork, go fix your code." moment. This isn't the sort of break where someone would see it and go "Oh yeah, assuming NULL is anything other than nullptr is dumb!"
Why not? We've broken the dork who used undeclared functions, void main, gets ...
(It's the same funking dork anyway. You know who you are, I'm looking at you!)
Note that
int x = ((void *) 0);
will actually work in GCC and get you a zero into x, just with a conversion warning. The dork is unaffected; their code works and they don't read warnings.It is today, but idioms are a human concept and who knows how things will be in 2033?
The printf example you gave is an example of garbage in, garbage out. If NULL is a macro not defined as a pointer sized integer, then you're at fault here.
Yes, it does.
> If you're programming in C, you usually define 0 as an invalid value, or a null value.
That was also the usual pattern in C++ when there was no alternative. Once nullptr was introduced in C++, NULL or 0 quickly became a code smell.
> C doesn't have the insane type system C++ has and doesn't have a very strong need to make a distinction between a pointer or an integer, since they're all in the end numbers.
C++'s type system is far from insane. It's actually one of it's killer features.
You're both entirely oblivious to the need to not conflate pointers with integers and failing to present any case in favour of the legacy and broken use of NULL, and in the process failing to address all family of known error patterns involving it.
> The printf example you gave is an example of garbage in, garbage out. If NULL is a macro not defined as a pointer sized integer, then you're at fault here.
Again, you seem to be completely oblivious to the problem domain. NULL is not a macro as far as C or C++ compilers are concerned. NULL is a magic constant that's resolved at preprocessing time. Replacing NULL with nullptr means a magic constant is replaced by a concrete type, and thus whole family of errors can be avoided with compile time checks. Claiming that the developers who wrote in bugs are at fault for inadvertently adding bugs makes no sense at all because it does not solve any problem at all, and instead is just cynical finger pointing. I take compile-time checks over unhelpful finger pointing all day every day.
The original mistake by the standards committee was allowing implicit conversions from integer to pointer. I.e. allowing NULL to be defined as simply 0.
If NULL had been defined always as ((void *) 0) then I don't see that we would have had a problem.
But that's all history now and in this situation I can see that adding nullptr becomes a reasonable way out.
It's ironic though that the fix for the different ways to write null is to add yet another way.
If it was you who wrote stdlib.h, sure; otherwise, if you’re on a platform where NULL is traditionally defined as 0 and not (void *)0, you’re stuck. A conformant implementation is free to use either definition.
If you want to language-lawyer more heavily, C does not require there to be pointer-sized integers (uintptr_t is optional), does not require that all zero bytes represent a null pointer in memory (unlike for integers), does not require that the implementation choose to store an integer with value zero as all zero bytes (there may be other valid representations), and in any case does not require an implementation to do anything reasonable at all if the caller passes an integer but a vararg callee looks for a pointer (think separate integer and pointer registers).
[I’m not entirely sure if (void *)(void *)0 is a null pointer constant (though it’s certainly an expression that evaluates to a null pointer)—does it count as a zero-valued integer constant expression cast to a pointer to void? So you might not even be able to use (void *)NULL as a hedge against bad platform headers.]
#undef NULL
#define NULL ((void *) 0)
Just don't do it prior to the inclusion of any standard header (C or POSIX).There is no difference between
char *p = nullptr;
and char *q = 0;
other than the variable name; the two have to compare equal: (p == q).What's wrong with 0 is that when it's not in an expression where it's being converted to integer type, it's just an integer.
int *p = 3;Technically NULL == 0 always because the standard special-cases zero-valued integer constant expressions; (uintptr_t)NULL == 0 or NULL == *(void **)calloc(1, sizeof(void *)) is another matter :)
Language lawyering aside, a non-all-zeroes representation of NULL will probably blow up most C programs [e.g. static-storage-duration initialization is now not the same as calloc or memset(,0,) and is even type-specific]. Like CHAR_BIT, that’s a joint that technically exists but has been rusted for decades (pun not intended).
Apparently some compilers specified a special __null extension to handle that case before nullptr was a thing.
Particularly when using structs this removes a lot of ambiguity if you ignore the indirection to find out the underlying type of the enum (or encode it in the name hungarian style).
enum D : uint8_t {
A = 0,
B = 1,
C = 2
}
typedef struct {
D f;
} __attribute__((packed)) E;
assert(sizeof(E)==1);
etc. could make grokking protocol declarations with enums less onerous and requiring one less level of indirection.There is a downvote button.
The HN Rust Gang will find you.
Joking aside, I've a healthy amount of respect for rust, and I hope that many of the ideas make their way into other language. The terseness, heavy use of macros, _insane_ compile times (and that's coming from someone who writes templates in c++), general assumption that you're on Linux from third party crates, and IDE support combine for something that just isn't usable for me just yet. Maybe in a few years!
https://news.ycombinator.com/item?id=35813821 ("New C features in GCC 13", 11 days ago, >260 comments)
You can read #13 of the Charter https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2086.htm
As for the audience, it's all the C developers, the open-source and commercial compiler implementations, vendors of libraries, tooling, services, learning material and everything else built in C; which is just innumerable.
Each Standard version released supersedes and obsoletes the previous versions. Intentionally, the versions are meant to be as backwards compatible as possible so that one can mix and match C89/C99/C11 codebases with minimum effort.
C has gained only a handful of features in the last 40 years. Compared to the great many things that are improved w.r.t. undefined/implementation-specific/unspecified behaviors, or removed to keep up with modern times (e.g. Trigraphs, Two's Complement integer representations, etc).
I'd say: (1) upgrading is not the spooky thing people make it out to be. Go, Rust, they all move much faster than this and have very ambitious big design ideas on their mind. (2) It's necessary to take good care of C as it, and the things built in it, will realistically outlive many of us.
Folks like myself who use C to write system software.
> Is this stuff likely to make its way through to embedded toolchains?
Embedded toolchains based on GCC or Clang will presumably see these features one day.
In the same way that Rust used underlying `const` attributes in LLVM (and found all the weird edge cases), and Nim used C as an intermediate as have many other lisp or object-ish languages.
This feature composes with _Generic macros quite well:
#define div(X,Y) _Generic((X)+(Y), int: div, long: ldiv, long long: lldiv) ((X), (Y))
auto res = div(38484848448, 448484844);
auto a = b * res.quot + res.rem;
It also lets you get rid of all the "typeof(X)" foo in macro definitions.Er, a much better approach is to allow unnormalized Unicode in source code and use form-insensitive matching of symbol names so that all forms of a symbol are equivalent. This can be done by normalizing during the parse, or by implementing form-insensitive string comparison and hashing functions that normalize glyph by glyph as needed -- the latter can be very fast for all-ASCII and mostly-ASCII symbols!
The reason this is a better way is that there's too many places that don't produce NFC. For example, HFS+ uses NFD, so if you cut-n-paste a file name from HFS+ into other contexts, you'll be pasting NFD unless the cut-n-paste system normalizes to NFC. Also, while it's true that input modes typically produce NFC, it's more that they produce NFC for a small subset of Unicode, not that they will normalize other forms seen on input. Using form-insensitive string comparison/hashing/matching yields a better user experience at not that much implementation cost: you're gonna need a Unicode library, and that library will need to have normalization support, so you can implement form-insensitivity.
Linkers will often be blissfully unaware of Unicode or any form of localization. This was the impetus for UTF-8, so that the bulk of software which is 8-bit clean or which operates on opaque, NUL-terminated strings can continue working as-is. This can't be changed without breaking backwards ABI compatibility; therefore, it's very unlikely to change.
There are countless half-measures that could be taken, but few if any are suitable for standardization. If the history of software localization is any guide, in the face of strict, forward-looking specifications various vendors and ecosystems will likely go there own way, with the one sure thing being a failure to fully adopt or properly implement the specification.
I'd rather have a seperate 'recode' to NFC preprocessing in the build process, if the developers editor doesn't do NFC normalization.
if I'm not mistaken checking for NFC is simpler than transforming to NFC, right?
I really wish C++ had Rust style enums. Having to implement them with flags in C++ is a bit of a chore.
Lambda: https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2892.pdf Defer: https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2895.htm
https://en.cppreference.com/w/cpp/language/nullptr
sorry - thought the post was re c++ - my bad