by lisper · 2y ago · 0 comments
Pointer decay is a fundamental mechanic in C. If you use arrays in C, and you pass said arrays as an argument to a function, then you are dealing with pointer decay.
It will accept any existing C program unmodified.
With a per-file switch, say, #define __FEATURE_WEAK_ARRAYS, it will start to discriminate T* and T[], make it an error to mix them in assignments, or to pass one instead of the other if both the function definition and the function call are in files with this feature on. It will not complain about functions defined elsewhere.
Then, say, #define __FEATURE_STRICT_ARRAYS the compiler will complain about mixing arrays and pointers as function arguments, no matter where the function is defined. It would require updated stdlib headers, for instance.
Additionally, #define __FEATURE_MULTI_ARRAYS would enable syntax for fixed-size multidimensional arrays, Fortran-style. Now uint8[3][2][10] foo; would allocate 60 elements, and access to foo[1][2][3] would involve one memory dereference, not three.
More support would be needed: sizeof, support for slices, safe array copies and length checks. Nothing extraordinary.
Having this implemented would make a terrific master's degree work.
There are also probably a ton of edge cases you haven’t thought about yet. For one thing, your T[] would be a different beast depending on where it appears—if you declare a variable in a block as T[], it’s an array, but it sounds like your proposal has different semantics for T[] in function parameters—it’s a reference type.
void f(int x[]) {
int y[] = {1, 2, 3};
y = x; // is this allowed?
}
I’m not trying to fight over the specifics of your proposal. I just want to illustrate that the language design is a tapestry, and you’re pulling at one of the threads.There are a few proposals I see like this that circle around. This is not the first array improvement proposal I’ve seen for C. There are also lambdas / closures, which are surprisingly untenable in C when you really dive into it. There’s sum types / discriminated unions in Go, and higher-kinded types in Rust. For each of these features, you can find languages which already have these features, giving you all sorts of templates for how to build it, and yet it’s still such a pain in the ass to add these features to the languages which lack them.
This has been studied for decades; there have been many attempts to build a safer version of C. And eventually the C standard committee will have to decide on an approach or lose out to newer languages at an increasingly accelerated rate.
I'd say that C will lose relevance slowly, more and more, as much as Zig will gain relevance, hopefully to the point of becoming the default choice, and having key parts of Linux kernel ported to it. Not Rust, which mostly replaces C++; even though it can venture on the C territory, its not comfortable nor seamless there. Zig is so seamless, it can even compile your C code along the way. It can do gnarly stuff like handling memory-mapped control registers with relative ease, and with much fewer footguns than C.
C is old, and its age shows. It needs to gradually retire, the way Fortran-77 did.
T value = foo[1][2][3]; // becomes:
foo -> (T **)
(T **) -> (T *)
(T **) (T *)
... (T *) -> (T)
(T *) (T)
... (T)
(T) <-- This one!
This allows for jagged arrays, yay! So useful.This is in stark contrast to a Fortran-style array, which is allocated as one contiguous piece, all dimensions folded up for linear access with one dereference.
You could if you introduced a new type of "safe array".
e.g.
int[] is a traditional C array which decays to int*
int[@] is a "safe C array" which is syntactic sugar for struct { size_t __count; int* __items; }, and as such can't decay
int[] and int[@] would not be directly interoperable, except by converting both to int* – maybe casting an int[@] to int* would automatically extract the __items member.
(The [@] syntax was chosen at random, if you don't like it, pick something else.)
Most things just take a pointer.
Wouldn't be easy by any means but it could be done at the scale of the Linux kernel if anyone cared enough.
But if you are willing to use something-like-C-but-not-shackled-by-backwards-compatibility, then why stop at arrays and pointers? Just move all the way to D or Zig (or even Rust). These are all languages designed (partially) so that you can port an existing C system bit-by-bit over into them.
Many people who can afford that, are doing that, of course. And that's why you don't really hear much about backwards incompatible developments for C. What would be the point?
Says who? Non-backwards-compatible changes are made to language standards all the time. It's not pain-free, but neither is the status quo.
Besides, who cares what the language is called? Change the name if that's what it takes, but stop conflating pointers and arrays. The cost of that has been literally billions of dollars in losses due to buffer overflows over the decades.
And of course there is C++, the most famous attempt to fix C in a somewhat compatible way by adding more features. It is debatable whether this effort resulted in a better language. C++ has all the bits needed to check array bounds by default but chooses not to do so...
The problem is that the huge existing stock of C code is written in C and not rust, zig, D, etc. The same would be true for your proposed "better C" language and any other incompatible iteration of C.
If you can come up with a way to add these guarantees to C without needing significant rewriting, I can assure you that most C programmers would be very interested.
All of these are very different from C. What I'm proposing is just one small change to the existing C language.
> If you can come up with a way to add these guarantees to C without needing significant rewriting, I can assure you that most C programmers would be very interested.
I can pretty much guarantee that they would not because this is easy: phase in the changes. Start by turning array-pointer conflation into a mandatory warning rather than undefined behavior or whatever it is now. Then wait a few years. Then turn it into an error that you can muffle using -C2024 or whatever.
I actually don't know whether array-pointer conflation is required by the standard or if it's undefined behavior (I'm pretty sure it's one or the other). But if it's the latter then you don't actually have to change the standard to make this happen, all you need to do is write a compiler that does the Right Thing. AFAIK no such compiler exists. But there is just no excuse for this:
% gcc -v
Apple clang version 14.0.0 (clang-1400.0.29.202)
...
% more test.c
int main () {
int x[10];
return *(x+20);
}
% gcc -Wall test.c
%std::array::at does bound check.
I feel like the amount of effort that has been spent so far to make C safe and fix bugs due to C not being safe is greater than the effort that would have been required to rewrite all existing C code into memory safe languages.
But I think secretly C programmers don't want memory safety. Dealing with pointers and remembering to malloc and free are part of what makes them feel more skilled/elite than those other programmers who have garbage collection and bounds checking.
How much, do you think, would rewriting all existing C code cost?
For me problems with C are as follows:
1. Inadequate standard with lots of unspecified behavior. I want behavior matching my architecture. Wrap my integers, always. I want my bit fields to be laid out in a predictable way, so I can actually use that feature to work with protocols rather than using shifts and bitwise operations. I must not research whether compiler will throw away my `while (true)` loop. Compiler must be predictable.
2. Bad standard library backed by the language standard (so I can't just throw it away, compiler will replace my loops with memcpy or will replace any standard library call with particular semantics).
3. Unexpected runtime cost. For example global variables are initialized to zero and that requires special code inserted before main.
4. Bad syntax. Switch must not allow fall-through, not by default anyway. `()` must be treated as function with zero arguments, not as a function with unspecified arguments.
5. Lack of namespaces and modules.
I definitely don't want compiler to track array lengths. C is not Rust.
Not hugely relevant but zero initialised globals don't imply code inserted before main. They get allocated at link time into a continuous blob which is zeroed by the loader. Non-zero values take up space in the binary but also involve no code generation. Global constructors, C++ style, usually do involve walking an array of function pointers before main though.
Null-terminated strings are bad, but there's nothing about the language (other than the standard library and literals) that forces you to use them. There are several alternative implementations[a][b].
1 is true, but the modern interpretation of UB is against the spririt of the original standard, even though it's according to the letter of it. It was meant to mean exactly what you're talking about, but got optimized into oblivion later.
2 is what I'd say is the main problem with C. The library is truly awful, to the point where I treat all of it except the mem* functions and maybe exit deprecated.
3 is not true; look up how the BSS segment works (it might be true on Windows, I don't know, but that's not really a very good C implementation, since it's for C++ primarily).
4 is true for a reason; pre-standard C didn't have function prototypes. This was invented by the standard, to much rejoicing. But they needed compatibility, so that's where it comes from. Switch cases are really labels, and that's why they fall through. If C was more actively developed (read: less stable) these would have already been fixed, by deprecating them and creating replacements.
5 is not something I usually care about much. Write one header file per module, don't include headers from other headers (declare anything you need in the header itself, the compiler allows it) and just prefix each exported function with foo_ or something like that. It's not that much trouble, and you get multiple .c-files pre module, which some languages don't allow.
The thing is that, in order to fix most of those issues, you'd either break backward-compatibility (and fork the laguage) or break most existing implementations (and lose all support). Making a new language is much easier.
As for tracking lengths, I mostly agree. If the length is statically known, that's perfectly fine. But dynamic lengths shouldn't have hidden tracking. Still, the C99 solution isn't that great, and I can't see how else to do it.
[a] https://nullprogram.com/blog/2023/10/08/ [b] there was a fat-pointer string library, but I can't find it now
I'm not aware of operating systems implementation, but I doubt that there's some magic to provide zero-initialized memory. To zero out memory, you need CPU work. Probably OS won't reuse memory because of security reasons and will need to erase it any way.
That's not a big issue, of course. With some linker tinkering you can declare truly uninitialized global variables. Not "standard C", but whatever.
I'm not sure if this is true. All kernels rely on stacks and queues to manage processes and scheduling. They're all implemented as arrays.
It's not true AT ALL. Show me a kernel that doesn't deal with buffers. Buffers clearly have array semantics. Even microkernels with a minimal API surface map and copy between buffers.
But its still beyond me how in decades of programming the C people somehow haven't had the idea of a pointer+size type. Whether you call it a slice, span or a view, doesn't matter. Why do I have to manually pass a size everywhere, it's such a common case, why is there not a common solution??
Are the people writing the standard just afraid of change? Seems to me, especially when it comes to things that could resemble new syntax. Sidenote why does _Atomic look like that?
Then use assembly. C is meant to abstract CPU architecture away.
Maybe. Looking back, I'd describe C as a portable assembler. K&R only optimised CPU architecture away when it was efficient to do so. For example, it wasn't efficient to specify the signed-ness of a char - so they didn't. Likewise the result of modulo ('%') on a negative number was undefined. Even the size of an int was undefined. In all these cases you get what the hardware gives you - just like you do in assembler.
I think that was the right decision. It was the best that could be done at the time. The price of the abstractions languages put in place in the name of safety and convenience meant they were a poor fit for embedded and system work. Consequently C has had decades of dominance in it's niche, a success that speaks for itself. Now a plausible challenger has arisen, but it's taken forever in internet time.
What I will criticise is what came after K&R. In K&C Undefined Behaviour meant "you get what the hardware gives you". Since what the hardware did was always well defined with a given compiler and arch everything the behaviour of your code was 100% deterministic. Then the compiler writers seeking to produce faster code twisted the definition to mean "if the behaviour is undefined we can do whatever we damned well please in order to generate faster code". And with that, at different optimisation levels code started to do different things.
The C++ plumbed the depths of this idiocy by definite infinite loops as UB. I have no idea why - embedded computers, services on modern OS's and even OS's themselves have infinite loops at their core - loops running until the electrons are removed is exactly the behaviour the programmer is depending on. It's idiocy because the halting problem (and ergo whether a particular loop is infinite) is famously not decidable. So they've undefined behaviour in a way that itself isn't defined. In practical terms, this means you write an infinite loop you are making a bet some you've made so convoluted a future version of the optimiser won't spot it. It's a bet some the occasional person has lost when they moved to a new version of the compiler. It is possible to signal to the compiler the loop must stay regardless, but you have to be a language lawyer to know how, and most don't.
So yes for today's C you are right, it is not assembler. In some ways it's objectively worse, as assembly is always well defined.
No, what you are talking about is "implementation-defined". Out of all trades, programmers should know better than everybody else to code against the specification rather than the implementation. If your code worked with K&R compiler by chance, and not by contact, then your code is wrong. Period.
I'd love C-like language which compiles to assembly in an understandable way. I mean that optimizations are certainly useful and needed. I want to write `24 * 60 * 60` and expect for compiler to multiply those values at compile time. I want to write debug logging which could be disabled for release build and all relevant variables and functions be excluded. Basically there are reasonable optimizations which I would expect for compiler to do.
Anyway it's not like there's a choice in reality. Manufacturer provides SDK and examples with C, using another language for most projects is not realistic.
And using C as fully deterministic is idiotic, considering the effort that went into specifying in great details everything that is NOT deterministic.
> I'd love C-like language which compiles to assembly in an understandable way.
Which is orthogonal to its purpose. A compiler's job is to provide the fastest code that implements what your (correct) code specified. Readability is pointless for generated code, as it not meant to be read nor modified.
void f(int len, char s[len]);
void g(float m[static 16]);
The first one is for variable-length arrays, the second one for fixed-length. TCC even implements array bounds-checking.But because a lot of people were stuck using C89 for several decades (due to old compilers), and the syntax isn't that great, nobody even knows they exist.
Personally, I think Dennis Ritchie's[a] proposed syntax[b] was much better:
void f(char s[?]);
[a] The creator of C.Linux kernel maintainers certainly do - they even invented a non-standard extension of C99's VLA notation (their own invention, not implemented in GCC)... In newer versions of the package "Linux man-pages", most libc functions are documented using a non-standard extension of that syntax. For example, the prototype of memcpy() now reads [0]:
void *memcpy(void dest[restrict .n], const void src[restrict .n], size_t n);
It means this function accepts two arrays (dest[] and src[]), with n bytes of data type "void", src[] is read-only ("const"), and both src[] and dest[] are non-overlapping ("restrict"). Two non-standard notations are used here: a "void" array with elements of unknown type (not allowed in C99), also, ".n" means "a variable in the argument list, but defined after this variable" (which is not allowed in C99).The equivalent C99 definition would be something similar to:
void *memcpy(size_t n, char dest[restrict n], const char src[restrict n]);
As more people are exposed to these man pages, the C99 syntax hopefully will have more publicity. Finally, C23 interestingly states that:> 15. Application Programming Interfaces (APIs) should be self-documenting when possible. In particular, the order of parameters in function declarations should be arranged such that the size of an array appears before the array. The purpose is to allow Variable-Length Array (VLA) notation to be used. This not only makes the code's purpose clearer to human readers, but also makes static analysis easier. Any new APIs added to the Standard should take this into consideration.
[0] https://git.kernel.org/pub/scm/docs/man-pages/man-pages.git/...
[1] https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2611.htm
Optionally (command line option '-b') though and (somewhat perplexingly) only at run-time. The documentation hints at the run-time performance (and code size) impact.
But any compiler that does constant propagation, inlining and (ideally) integer range analysis can optimize away most run-time bounds-checks already. If GCC or clang did it, it would probably be fast enough.
https://digitalmars.com/articles/C-biggest-mistake.html
(and of course the problem wasn't new 15 years ago either.)
It wasn't fixed then. It won't be fixed now.
C is valued for not changing. C is valued for backwards compatibility with the most obscure platforms with unmaintained compilers.
The C userbase is self-selected to like C exactly the way it is.
Some people will want to store the size in a type smaller than size_t (and potentially place it not adjacent to the data pointer for better packing in a struct; or perhaps even bit-pack it). Some will want to place the size relative to the data instead of the pointer (esp. flexible array members). Some will want to store half (or a third, etc) of the element count, the array being used as multiple back-to-back arrays. Then you'll have questions on pointers in the middle of an array, indexable by positive and negative indices. Never mind the pretty significantly increased register shuffling of having to pass the size across functions.
For projects that are fine with doing things in the single way forced upon you and don't care about how things are done as long as it's safe, C is already rather clearly not the language to choose.
C++ as-is can already pretty trivially allow adding bounds-checked array types, and compilers can even be configured to warn on all pointer indexing (https://godbolt.org/z/W8sqGW5sh), achieving the entirety of your proposal while not locking people into a single data structure. (granted, some may not want to expand to C++ "just" for one or two features (me included), but here allowing customizable array data structures is basically the only sane option, and C would have to take a rather significant amount from C++ to allow for such itself)
So? My point here is that this should be the compiler's responsibility, not the programmer's. Why could not a compiler bitpack the same way -- or even better than -- a programmer could?
Not a problem when passing the array by value (i.e. two registers of the data pointer and length), but then any packing automatically does not apply anyway.
PS: There was actually a quite recent bounds-checking proposal by (I think) Apple Clang folks that works with annotations and IMHO looks pretty good (in the sense of "I would actually use it in my libraries"):
https://discourse.llvm.org/t/rfc-enforcing-bounds-safety-in-...
Not that his proposal was perfect, but WG14 didn't even bothered to improve upon it.
Also saying that's "the main problem with C" seems to miss the mark. As a C programmer I wouldn't call this the crux of any particular problem. It's weird and problematic in multiple ways but surely not "the main problem".
Only, it would even be stupider if your grasp of programming was as great as your understanding of aerodynamics.
(Arrays do exist in the object model, and you can take pointers to them of type T (*)[N]; you just can't copy them around by value, and the name of an array decays to its first element pointer.)
Compilers just typically don't track array bounds at runtime because of (a) performance and (b) big ABI incompatibilities. There's nothing in the language itself that stops them.
But this is exactly the problem. UB can be anything, including nothing. This should be at the very least an optional warning. But here is what happens with a fairly current C compiler:
% gcc -v
Apple clang version 14.0.0 (clang-1400.0.29.202)
...
% more test.c
int main () {
int x[10];
return *(x+20);
}
% gcc -Wall test.c
% $ gcc -O2 -Wall -c t.c
t.c: In function ‘main’:
t.c:3:14: warning: array subscript 20 is outside array bounds of ‘int[10]’ [-Warray-bounds]
3 | return *(x+20);
| ^~~~~~~
t.c:2:11: note: at offset 80 into object ‘x’ of size 40
2 | int x[10];
| ^
Not sure how to get Clang to warn. It clearly recognizes the undefined behavior. $ gcc -fsanitize=undefined -o test test.c
$ ./test
test.c:3:10: runtime error: load of address 0x7ffea07fded0 with insufficient space for an object of type 'int'
0x7ffea07fded0: note: pointer points here
b2 55 00 00 d8 df 7f a0 01 00 00 00 c8 df 7f a0 fe 7f 00 00 00 00 00 00 00 00 00 00 62 0f 73 ea
^
> But this is exactly the problem. UB can be anything, including nothing.There's nothing stopping compilers from implementing the semantics you want (when not crossing an ABI boundary), and indeed, they've been adding more gradual hardening options that can be used in production. It's just that there's little demand for universal bounds-checking on arrays, and some users even want more flexible accesses, e.g., for operations like container_of.
On the other hand, people can and have made experimental forks of the Rust compiler to turn all panics into immediate LLVM-level UB, but the mere existence of such an option doesn't mean that Rust's bounds-checking is now worthless, as you seem to be implying for C.
also C programmers Wow, You are trying to compile this old program on new toolchain?
Here is a list of 10k errors due to changed defaults flags for compilation, dependencies breaking by going from 9.4.1 to 9.4.2 and also, your code contains platform-specific extensions anyway.
But C is portable guys! It really is!
E.g. consider the hemming and hawing about a 64-bit time_t. That's a tiny change in comparison, and one that's obviously unavoidable and with a strict deadline. And yet...
I had received a compiler warning about this when trying to compile a program on Raspberry Pi (it was a old version; I did this a few days before they implemented 64-bit time_t on Raspberry Pi). Fortunately I was able to add a macro to allow it to work on computers without 64-bit time_t. Other than that, the program I compiled worked perfectly, although I wrote the program on PC and did not specifically try to make it work with Raspberry Pi. So, a C code is portable, although sometimes a few changes are required to make the program to work.
But I think that 64-bit time_t is a good idea.
Once Zig becomes stable, I think it may have a chance of slowly fixing existing C code bases, by its virtue of being able to co-exist with existing code bases. On the other hand, a lot of C programmers don't want to change because they don't see a problem, so the presence of those will probably ruin any chance Zig has of improving the situation.
The change will be a generational one. C will never entirely disappear, but over time, C code will be old code. People will occasionally write new C for what amounts to aesthetic reasons, and there will be a robust niche (doubtless well-paid) of maintainers of legacy C projects. All the kernels currently written in C will still exist, and still be composed mostly or entirely of C.
But new work in embedded, drivers, implementation of programming languages, netork stacks, will be in Zig instead. With some Rust as well, but I figure we've seen enough of that arc to tentatively conclude that what Rust is displacing is mostly C++, not C.
But when I say generational, I mean it. You're quite right that there is a legion of C programmers who like it and intend to stick with it. But they'll retire one day.
Rust is already part of the Linux kernel, being used for rather complex things like GPU drivers in Asahi. Android rewrote their Bluetooth stack into Rust and Windows is actively replacing existing operating system components with Rust as well. I don't think we'll need to wait for Zig to start replacing old C code, it's already being replaced with Rust now.
I think Zig would've been a better choice for some parts, but it's taking too long to become stable for it to be included in large projects. Still, it may be useful for people working on embedded stuff, as embedded code seems to be stuck with 90s C when it comes to language support, if someone can manage to write a compiler backend for that specific embedded chip.
While Rust might be a better alternative, C++ is already much better than raw C.
Zig was introduced in 2016. If it still isn't stable 8 years later, I wouldn't hold my breath.
Zig lacks the corporate backing Rust had, though, so it's hard to say when they'll get stable.
Regardless, even if it'll take Zig a decade, I'm sure it'll have a stable release with decent memory management as part of the language spec before C will.
Bounds-checking can sometimes be useful, and can perhaps have a switch to control its working.
Some instruction sets (such as Flex) have tagged memory. In Flex, a pointer contains the address of a block (and a pointer can also be designated is read-only, disallowing writing through the pointer). There is also a "reference" consisting of a pointer and a displacement; I suppose this "reference" can be used to implement C pointers. If you use this, then the computer will automatically do bounds-checking and will result in an error if you make an access that is out of bounds.
Tagged memory also allows to easily find the pointers in memory without needing to know the types of variables, which can be helpful for some uses, e.g. to detect improper use of realloc/free. Furthermore, null pointer can be zero (without the tag bits), which is automatically an error when used as a pointer because it is not a pointer.
https://www.digitalmars.com/articles/C-biggest-mistake.html
Recent discussion: https://news.ycombinator.com/item?id=40392371
Discussion thread about the article, 10 months ago: https://news.ycombinator.com/item?id=36564535
Even Dennis Ritchie tried to add fat pointers, but failed to have the new C overlords care about his proposals.
Despite what we might think about their feature set, it is quite relevant that Alef, Limbo and Go were designed by the UNIX folks, and all of them don't repeat the same mistake with arrays and strings.