296 points · by lsof · 4y ago · 249 comments
Additionally Google spent several years paying to clean up the Linux kernel from all VLA occurrences.
Sadly, the C committee doesn't really understand what was wrong with VLAs and a sizable group of its members wants to make them mandatory again:
https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2921.pdf ("Does WG14 want to make VLAs fully mandatory in C23")
exhibit A: https://lists.freedesktop.org/archives/mesa-commit/2020-Dece...
exhibit B: https://github.com/neovim/neovim/issues/5229
exhibit C: https://github.com/sailfishos-mirror/llvm-project/commit/6be...
etc etc
What does 'mandatory' mean? Like if I write a C compiler without them... what are they going to do about it?
This isn’t much different from writing something like this in JS:
var a = [];
a[console.log("Hello"), 1] = 42;
except that this indexes the array as opposed to setting its length.The line:
typedef int T[n];
is the essence of VLA-ness, not `int A[n]`. The array of VLA type can have any kind of storage one wants.It can be stack
T a;
It can be heap T *a = malloc(sizeof *a);
It can be even infamous alloca() T *a = alloca(sizeof *a);
Please stop talking about this "VLA is stack-base vector" crap because it means that one does not understand what VLAs are about. I admin that automatic VLAs are pretty much always wrong but this use case is a tiny bit of the realy functionality of VLA types.VLA were added to language to handle multidimensional arrays.
And the really shine at this task. Even C++ has not good alternative for it. Vector of vectors is a really crappy data structure.
A few examples when working with square matrices:
- allocation on stack
float A[n][n];
- allocation on heap float (*A)[n] = malloc(sizeof(int[n][n]));
...
free(A);
- indexing A[i][j]
- passing to functions: void add(int n, float A[static n][n], float B[static n][n], float RES[restrict static n][n]);
...
Please show me something as simple, effective, self-documenting and elegant in C++.What could possibly be surprising about reusing the exact same object on every function call, especially when you default to an empty list, set or dict. Getting an actual empty list is as easy as defaulting to None and explicitly checking for it, so there isn't even a reason to do it any differently. /s
Who the hell thought that this was sane behavior in a language with mostly mutable objects?
Python default arguments are evaluated only once at function definition, not every function call. It's the source of one interesting WTF for anyone who assumes otherwise:
def foo(a=[]):
a.append(1)
return a
>>> foo()
[1]
>>> foo()
[1, 1]
>>> foo()
[1, 1, 1] #include <stdio.h>
// "puts" makes "f" not constexpr.
constexpr int f() { return puts("hello"); }
// error: size of array 'argv' is not an integral constant-expression
int main(int argc, char *argv[f()]) {}I'm uneasy about variable-length arrays at the best of times. It hadn't even occurred to me that you might have a variable-length array as a function argument.
This personal assertion holds no water.
People hold/held onto C89 because compilers like Visual Studio's C compiler failed to support anything beyond C89 for ages.
https://devblogs.microsoft.com/cppblog/c11-and-c17-standard-...
It's my understanding that Microsoft adopted a role in the C standardization committee that was a kin to sabotaging any update beyond C89.
Note that they aren't supporting the optional annexes and stuff like C atomics aren't supported.
[0] - https://herbsutter.com/2012/05/03/reader-qa-what-about-vc-an...
In the function definition, it seems to basically also decay to a pointer, except that the compiler adds basically an assertion that the value in the brackets is greater than zero to the to the top of the function. That actually seems quite weird to me.
I'd have been fine with the VLA acting like a proper local VLA with respect to things like sizeof, in which case the assertion makes sense. Or I'd have also been fine with it totally decaying to a pointer, making it just documentation. This half-way in between state is quite weird.
int foo(int n, int m, double x[n][m]) {
printf("sizeof(x[0])=%zd\n", sizeof(x[0])/sizeof(double));
}The only times I use it are when I'm writing something that requires ridiculous portability even to bizarre platforms and compilers. C99 is far more ergonomic in comparison, even if you have to avoid using some of the truly terrible design decisions that came along for the ride.
It means nothing. It's a baseless attemt at an appeal to authority that has no merit.
But the true Scotsman… uh, purist sticks to the K&R C as C89 has already lost some of the original elegance and simplicity. (Never mind that it’s a challenge since the general community has moved on.)
The caveat is that the standard doesn't guarantee these optimizations. But there are some non-standard __attribute__ declarations that can help with that.
Is this some portmanteau for “compile time optimization”?
Before it was all said and done you could enable a "deep compile" option that would even look at your java code for cases that would never execute - rarely execute (you're a dumb human right?) - etc and build an opinionated JS runtime around it for performance and size (size complexity? Space-Time-Trade-Off).
I was enamored with GWT for quite some time and developed a high level of skill using the tool. I still miss it frankly. People who seek to write one language and execute another are fundamentally insane. Even though this is basically necessary with a lang like C (one step above shifting bits and understanding instructions etc) those people still amaze me.
I'm glad I wasn't born with the requisite intellect to go down such rabbit holes myself. This makes me feel dumb and be OK with it at the same time.
That would be people who use compilers.
Though I do feel that this is something different from VLAs (no critique of the article though!). In my head at least the key factor about VLA is that you can allocate an array on the stack when the size isn't known at compile time. But that is not what the author does.
A VLA as specified in a function definition or a declaration (such as: void f(int n, float v[n]);) is known at compile time. And even if trickery is used to do a runtime-calculation of [n] the array itself is not allocated on the stack. And thus also not subject of the common criticism of VLAs.
So, at least in my opinion the arguments (discussed in this threadl) regarding VLAs is mostly orthogonal to the syntax (ab)used here.
void concat_strs(
int str1_len,
const char str1[str1_len],
int str2_len,
const char str2[str2_len],
char out_str[str1_len + str2_len],
);
void manipulate_array(
array_dim dim,
int arr[dim.x][dim.y],
);
Supporting things like printf() was probably not specifically desired, but it would be difficult to define it in such a way that it accepts all reasonable expressions and doesn't accept any "unreasonable" ones.The original purpose of VLAs is to let you stack-allocate an array with a length that is not known at compile time. In ANSI C you must heap-allocate such arrays, using malloc.
[1] https://www.open-std.org/jtc1/sc22/wg14/www/wg14_document_lo...
It's a landmark and incredible language, but it's chock full of potholes and foot-shotguns (footguns that blow off your entire leg). Even huge companies can't get it right, which makes sense. It started as a language basically without guardrails, and because of the extreme deference to the holy backward compatibility, it's more or less always going to be that.
Usually developers stick to known patterns and subsets. Sure, you can write "clever" code that's more aproppriate for IOCCC than as system-critical code, but that's the case with most programming languages.
There is such a thing as "bad code" and "good code". A lot of code linters can catch "code smells", and features can often be disabled at the compiler level.
On the other hand, not having to resort to inline assembler or writing 500x the amount of code in some cases is why we have such features. Complex features are useful in some (complex) cases, but are not to be overused.
There are very few footguns in C, compared to (say) C++ (or Python).
I can guarantee you that no employed C developer is putting IOCCC type code into shipping products. Pick any language you like, and turn up the code golfing to 11, and you'll be equally horrified.
Challenge accepted. I pick the Go language, here are my answers:
https://codegolf.stackexchange.com/users/7815?tab=answers
people complain about how verbose Go is, but to me that just means its readable. Even golfed, its pretty clear what is going on.
Nowadays, people are used to thinking entirely inside the abstraction provided by the language spec, but that was not the case in the '80s and early '90s. The boundary between the C language model and the underlying machine architecture was porous. You would include snippets of assembly language in your C code, if you wanted to do something more quickly than you thought the compiler could do it; and your C code would take full advantage of your knowledge about the underlying memory layouts, calling conventions, register usage, and so forth.
It did not really matter that there were gaps in the "C machine" abstraction because nobody was really programming against the "C machine"; they were programming against their actual hardware, using C as a tool for generating machine code.
Now that compilers know cleverer optimizations, undefined behavior is often impossible to reason about because the compiler can change your logic into something else that is more optimal and is equivalent to your logic only in well-defined cases.
In addition the entire idea of introducing undefined, unspecified and implementation-defined behaviors was to let existing implementations do, for the most part, whatever they were already doing while still being standards conformant (ok, the rationale's exact words is to "allow a certain variety among implementations", but in practice C compilers already existed in 1989 and the companies behind them most likely wanted to call them as "C89 conformant" without having to make significant changes).
C89 didn't define undefined behavior because that wouldn't make sense, but it did define what it means and going by the C89 rationale about what it was meant to be used for, clearly the idea wasn't the extremist "breaking your code at the slight whiff of UB because optimizations" but "letting you do things that we can't or don't want to define while keeping our own hands clear".
The "letting you" bit is important which is why they have the distinction between "strictly conforming program" and "conforming program" (i.e. minus the "strict") - which essentially has the former only be for "maximally portable" programs and the latter being "whatever conforming implementations accept", with conforming implementations being any C implementation that can compile strictly conforming programs - regardless of any extensions the implementation may have as long as these do not affect the strictly conforming programs.
In other words it was C89 Committee's way of saying "a (conforming) C program is basically anything a C compiler compiles as long as said C compiler also compiles C programs that adhere to the strict conformance we defined here" - which BTW flies in the face of the entire idea that introducing a single instance of "undefined behavior" makes the entire program not "valid C" anymore (after all program with undefined behavior can still be a conforming program as long as it is accepted by a compiler that also accepts strictly conforming programs).
This is the sort of circular self-referencing logic you get when committees try to standardize something that already has a bunch of not necessarily compatible implementations while also trying to not ruffle the feathers of the companies behind them too much.
It'd be an amusing tale if only some people (who you can ignore anyway) didn't get into fights about what page x, paragraph y, verse z of the Standard[1] say and decades later funneling that logic into compilers (which are somewhat harder to ignore) that break existing working code while Bible thumping their standards book whenever someone goes "WTF, this thing used to work before i upgraded the compiler"[3]
[0] http://www.lysator.liu.se/c/rat/title.html
[1] Capitalization Intentional
[2] Yes, C was considered one at some point :-P
[3] "No, it is not valid C, it couldn't have worked. You clearly imagined it."
Isn't it legal to fall of the end of the end of a non-void function, only just defined as UB to use the return value?
> If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.
> Otherwise, flowing off the end of a function other than main or a coroutine ([dcl.fct.def.coroutine]) results in undefined behavior.
https://timsong-cpp.github.io/cppwp/n4868/stmt.return#2.sent...
edit:
This also manifests in compiler optimizations, at least in gcc
Nice to see some vindication - I remember saying this and IRC pedants trying to argue up and down that they're absolutely not the same
amusing to think that the goal of them is probably to make it easier avoid buffer overruns, but then they can just be extended themselves to cause similar problems anyway.
It does preclude Turing completeness. The stack has an upperbound of the size of a pointer times the word size.
That is, could you build a compliant C implementation that implements a stack using an infinite memory (e.g. in a delay loop between the user and a mirror moving away through space), where each entry in the stack contains a convenient sized value (word, byte, whatever) and a tag? If the tag is clear, the value the contained directly in the infinite memory; if the tag is set, then the value is indirected into a fixed-sized memory. On taking the address of an item on the stack, if it is not already indirected, relocate it and indirect.
Of course the mechanism for doing stack unwinding on return needs to use relative operations ("drop five elements") and not chase frame pointers, but that seems trivial.
I admit I'm not super-familiar with all the details of the C specification, but it's not obvious to me that this would violate spec, and it would be Turing complete.
C isn't Turing complete without `fseek` (as far as I can tell).
Turing completes requires you to be able to read/write from an infinite tape (essentially infinite memory). This isn't possible in C, because `sizeof` is a constant expression, thus limiting the size of any type, and importantly also pointer type, to a finite number, thus making the addressable memory finite.
From what I can tell, the only way you could theoretically access an infinite tape is using `fseek` with `SEEK_CUR`.
There might be more shenanigans possible with `stdio.h`, but I'm pretty sure C can't be Turing complete without the `stdio.h` function (assuming no special language extensions).
If anybody is wondering, the preprocessor isn't Turing complete either, because you might theoretically have infinite memory, but then you only have finite recursion, which also isn't enough for Turing completeness. File iteration can have infinite recursion, but can also only carry over finite state between `#include`s.
Edit: I'm not talking about any real world implementation, but rather about the theoretical bounds of the C abstract machine.
I should've explained that I'm not talking about a physical implementation, but about the theoretical bounds of the C abstract machine.
> size_t can store the maximum size of a theoretically possible object of any type (including array).
In a proper theoretical turing machine, size_t would allow you to create and address arbitrarily large arrays too.
1. As https://www.open-std.org/jtc1/sc22/wg14/www/docs/dr_260.htm helpfully points out, "If two objects have identical bit-pattern representations and their types are the same they may still compare as unequal", and "[implementations] may also treat pointers based on different origins as distinct even though they are bitwise identical". It can thus be argued that, with a rather strict definition of provenance (i.e. how pointer values may be constructed), one could construct an implementation where every byte of every pointer is tagged with additional unbounded data that lets the whole pointer be properly dereferenced (I say every byte so that you're able to convert the pointer to an integer and convert it back to the same valid pointer), and where, as allowed by DR 260, pointers that have identical observable bit-pattern representations might not compare equal if they point to different objects. Thus, that implementation could create an unbounded amount of pointers.
2. Spawning off another thread and using infinite recursion (C has no defined recursion depth limit, and if you want to argue about automatic variables needing addresses or whatever and that the as-if rule doesn't cover that, there's `register` which makes address-less variables) to have two pushdown automatas that can together work as a Turing Machine.
3. Using variadic arguments. With `va_copy`, one can iterate through variadic arguments multiple times, and thus `va_list` can be used to implement a mechanism equivalent to pointers without actual pointers (any sane implementation probably uses a pointer for `va_list` somewhere in it, but that's not a problem here) and thus make a pushdown automata with 2 stacks
2. The problem with that is that you may have infinite recursion, but you can only pass finite amounts of memory between recursion steps. This has also been addressed by https://cs.stackexchange.com/a/60978.
3. I don't follow, how could you create a growing `va_list`?
Edit: Actually, I think I do now, so you essentially create a sort of linked list of `va_list`s?
1. This is probably correct. You'd need to be able to round trip through a void*, but that could still be implemented to retain the tagged data. I thought of pointer tagging more in terms of marking addresses with certain memory protection properties, but what you suggest should be possible. There may still be some wording disallowing it, but I couldn't find it.
If I have two stacks (by spawning another thread), don't I have two PDAs ? That's what that stackoverflow post indicates, and IIRC two PDAs are equivalent to a Turing machine.
Who said it had to be finite in theory? `size_t` is defined in terms of the implementation, not in terms of bit-widths.
Sure, size_t is finite in practice, but then again, so are all other programming languages. In theory, there is no upper limit on size_t.
> the unsigned integer type of the result of the sizeof operator (https://port70.net/~nsz/c/c11/n1570.html#7.19p2)
`sizeof` returns the following:
> If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant. (https://port70.net/~nsz/c/c11/n1570.html#6.5.3.4p2)
So `sizeof(size_t)` must be a concrete integer constant for any given C implementation, it can't change at runtime.
As far as I'm aware, there isn't an instance of an infinitely large integer, even in mathematics, there are finite integers and there is the concept of infinity.
I didn't say it has to change at runtime, I said that there is no upper limit on it in theory, because the upper limit is specified in terms of the implementation, and a a theoretical implementation with no upper limit on memory means that there is no upper limit on size_t.
Besides, I also said:
> Sure, size_t is finite in practice, but then again, so are all other programming languages.
Using your definition of Turing complete (no upper limit on pointer, references or addresses), I cannot think of one popular language that would satisfy that definition. Can you?
They address that `ftell` must return a finite value, but don't mention that `ftell` can fail for specific FILEs:
> If successful, the ftell function returns the current value of the file position indicator for the stream
But FILEs don't necessarily have a "file position indicator":
> If a file can support positioning requests (such as a disk file, as opposed to a terminal), then a file position indicator associated with the stream is positioned at the start (character number zero) of the file, unless the file is opened with append mode in which case it is implementation-defined whether the file position indicator is initially positioned at the beginning or the end of the file.
They don't seem to discuss the topic further.
> Therefore we will here only consider C programs without I/O. (Our argument can be adapted to show that the programs that restrict I/O to reading stdin and writing stdout are Turing incomplete as well, but we will not do so here.)
So they don't address the problem of IO completely.
Given any theoretical C implementation and a strictly confirming program (that doesn't do io) I can theoretically trivially solve the halting problem.
Since the possible memory is constant for any given implementation, I can use the following algorithm:
1. Execute one instruction of the program
2. If the program terminated, goto 4.
3. insert entire program state into a hash table
if it is already in the hash table, goto 5.
otherwise, goto 1.
4. The Program terminates5. The program never terminates
The above algorithm solves the halting problem of any C program with a constant memory bound in finite time.
And yes neither is infinite, so every computer is just a DFA, and lseek changes nothing. But given the amount of memory that exists we approximate and say they are Turing machines since there is enough memory to do most what we need.
fputc('L', tape_control);
c = fgetc(tape_data);
fputc(d, tape_data);
or a single file with controls disjoint from the tape symbols.Pointer—-
These do the same to pointers…
(Of course on a real machine the malloc() will fail at some point.)