829 points · by rseacord · 6y ago · 962 comments
We are members of the C Standard Committee and associated C experts, who have collaborated on a new book called Effective C, which was discussed recently here: https://news.ycombinator.com/item?id=22716068. After that thread, dang invited me to do an AMA and I invited my colleagues so we upgraded it to an AUA. Ask us about C programming, the C Standard or C standardization, undefined Behavior, and anything C-related!
The book is still forthcoming, but it's available for pre-order and early access from No Starch Press: https://nostarch.com/Effective_C.
Here's who we are:
rseacord - Robert C. Seacord is a Technical Director at NCC Group, and author of the new book by No Starch Press “Effective C: An Introduction to Professional C Programming” and C Standards Committee (WG14) Expert.
AaronBallman - Aaron Ballman is a compiler frontend engineer for GrammaTech, Inc. and works primarily on the static analysis tool, CodeSonar. He is also a frontend maintainer for Clang, a popular open source compiler for C, C++, and other languages. Aaron is an expert for the JTC1/SC22/WG14 C programming language and JTC1/SC22/WG21 C++ programming language standards committees and is a chapter author for Effective C.
msebor - Martin Sebor is Principal Engineer at Red Hat and expert for the JTC1/SC22/WG14 C programming language and JTC1/SC22/WG21 C++ programming language standards committees and the official Technical Reviewer for Effective C.
DougGwyn - Douglas Gwyn is Emeritus at US Army Research Laboratory and Member Emeritus for the JTC1/SC22/WG14 C programming language and a major contributor to Effective C.
pascal_cuoq - Pascal Cuoq is the Chief Scientist at TrustInSoft and co-inventor of the Frama-C technology. Pascal was a reviewer for Effective C and author of a foreword part.
NickDunn - Nick Dunn is a Principal Security Consultant at NCC Group, ethical hacker, software security tester, code reviewer, and major contributor to Effective C.
Fire away with your questions and comments about C!
https://news.ycombinator.com/item?id=22865357&p=2
https://news.ycombinator.com/item?id=22865357&p=3
https://news.ycombinator.com/item?id=22865357&p=4
(Posts like this will go away once we turn off pagination.)
- Locking down some categories of "undefined behaviour" to be "implementation defined" instead.
- Proper array support (which passes around the length along with the data pointer).
- Some kind of module system, that allows code to be imported with the possibility of name collisions.
There are efforts to define the behavior in cases where implementations have converged or died out (e.g., twos complement, shifting into the sign bit).
There have been no proposals to add new array types and it doesn't seem likely at the core language level. C's charter is to standardize existing practice (as opposed to invent new features), and no such feature has emerged in practice. Same for modules. (C++ takes a very different approach.)
Arrays with length constantly emerge among C users and libraries. They are just all incompatible because without standardization there is no convergence.
I'd argue that linked list might make a better candidate for inclusions, because I've seen the kernel's list.h or similar implementations in many projects and that's stuff is trickier to get right than stuffing a pointer and a size_t in a struct.
Passing a pair of arguments (pointer and a length) is surely one of the more universal conventions among C programmers?
One alternative to adding types is to allow enforcing consistency in some structs with the trailing array:
struct my_obj {
const size_t n;
//other variables
char text[n];
};
where for simplicity you might only allow the first member to act as a length (and it must of course be constant). The point is that then the initializer: struct my_obj b = {.n = 5};
should produce an object of the right size. For heap allocation you could use something like: void * vmalloc(size_t base, size_t var, size_t cnt) {
void *ret = malloc(base + var * cnt);
if (!ret) return ret;
* (size_t *) ret = cnt;
return ret;
}Recognizing common behavioral characteristics would actually improve the usability of arcane hardware platforms if there were ways of explicitly requesting the commonplace semantics when required. For example, if the Standard defined an intrinsic which, given a pointer that is four-byte aligned, would store a 32-bit value with 8 bits per byte little-endian format, leaving the any bits beyond the eighth (if any) in a state which would be compatible with using "fwrite" to an octet-based stream, an octet-based big-endian platform could easily process that intrinsic as a byte-swap instruction followed by a 32-bit store, while a compiler for a 36-bit system could use a combination of addition and masking operations to spread out the bits.
Would this involve further specification of bitfields? Feel implementation defined nature of bitfields limits potential
One thing that I'd really like to see would be some new categories of compliance. At present, the definition of "conforming C program" makes it possible to accomplish any task that could be done in any language with a "conforming C program", since the only thing necessary for something to be a conforming C program would be for there to exist some conforming implementation in the universe that accepts it. Unfortunately, the Standard says absolutely nothing useful about the effect of attempting to use an arbitrary conforming C program with an arbitrary conforming C implementation. It also fails to define a set of programs where it even attempts to say much of anything useful about the behavior of a freestanding implementation (since the only possible observable behavior of a strictly conforming program on a freestanding implementation would be `while(1);`).
I would propose defining the terms "Safely Conforming Implementation" and "Selectively Conforming Program" such that feeding any SCP to any SCI, in circumstances where the translation and execution environments satisfy all requirements documented for the program and implementation, would be required not to do anything other than behave as specified, or indicate in documented fashion a refusal to do so. An implementation that does anything else when given a Selectively-Conforming Program would not be Safely Conforming, and a program which a Safely Conforming Implementation could accept without its behavior being defined thereon would not be a Selectively Conforming Program.
While it might seem awkward to have many implementations support different sets of features, determining whether a Safely Conforming Implementation supports all the features needed for a Selectively Conforming Program would be trivially easy: feed the program to the implementation and see if it accepts it.
I think there's a lot of opposition to "optional" features because of a perception that features that are only narrowly supported are failures. I would argue the opposite. If 20% of compilers are used by people who would find a feature useful, having the feature supported by that 20% of compilers, while the maintainers of the other 80% direct their effort toward things other than support for the feature, should be seen as a superior outcome to mandating that compiler writers waste time on features that won't benefit their customers.
Realistically speaking, it would be impossible to define a non-trivial set of programs that all implementations must process in useful fashion. Instead of doing that, I'd say that the question of whether an implementation can usefully process any program is a Quality of Implementation issue, provided that implementations reject all programs that they can't otherwise process in any other conforming fashion.
Undefined behaviors tend to be undefined for a reason and shouldn't be thought of as defects in the standard. In my years on the committee, I have always argued to define as much behavior as possible and to as narrowly define undefined behaviors as possible.
We also had a recent discussion about adding additional name spaces (when discussing reserved identifiers), but it didn't gain much traction.
Consider signed integer overflow.
The intent wasn't that the compiler could generate nonsense code if the programmer overflowed an integer. The intent was the the programmer could determine what would happen by reading the hardware manual. You'd wrap around if the hardware naturally would do so. On some other hardware you might get saturation or an exception.
In other words, all modern computers should wrap. That includes x86, ARM, Power, Alpha, Itanium, SPARC, and just about everything else. I don't believe you can even buy non-wrapping hardware with a C99 or newer compiler. Since this is likely to remain true, there is no longer any justification for retaining undefined behavior that is getting abused to the detriment of C users.
For example, consider a very simple statement.
let array[10];
let i = some_function();
print(array[i]);
The function might not even be known to the compiler at compilation time if it was from a DLL or something.But the compiler is like "hey! you used the result of this function as an index for this array! i must be in the range [0, 10)! I can use that information!"
But we must write code that relies on the same rules and requirements that programs are held to (and vice versa). When either party breaks those rules, either accidentally or deliberately, bad things happen.
What sometimes happens is that code written years or decades ago relies on the absence of an explicit guarantee in the language suddenly stops working because a compiler change depends on the assumption that code doesn't rely on the absence of the guarantee. That can happen as a result of improving optimizations, which is often but not not necessarily always motivated by improving the efficiency of programs. Better analysis can also help find bugs in code or avoid issuing warnings for safe code.
I second this one. One of the best things from Rust is its "fat pointers", which combine a (pointer, length) or a (pointer, vtable) pair as a single unit. When you pass an array or string slice to a function, under the covers the Rust compiler passes a pair of arguments, but to the programmer they act as if they were a single thing (so there's no risk of mixing up lengths from different slices).
It is production-ready; if you want a dialect of C with arrays that know their length, you can use C++. If you wanted a dialect of C in 1993 with arrays that know their length for use in a production app you could also have used C++ then.
The problem with all these "can we add X to C" is that there is always an implicit "... but please let us not add Y, Z and W, because that would start to turn C into C++, which we all agree that we definitely don't want or need."
The kicker is that everyone wants a different X.
Elsewhere in this thread, I noticed someone is asking for namespace { } and so it goes.
C++ is the result --- is that version of the C language --- where most of the crazy "can you add this to C" proposals have converged and materialized. "Yes" was said to a lot of proposals over the years. C++ users had to accept features they don't like that other people wanted, and had to learn them so they could understand C++ programs in the wild, not just their own programs.
C shouldn't turn into C++, or even C++ Lite™, but it shouldn't remain strictly unchanging for all eternity, either. It should just always strive to be a better C, conservatively, because its niche is one where conservative advancement is important.
Some way to adopt programming practices that guaranteee consistent management of array and pointer length -- not just write code to check it, but actually guarantee it -- would, I think, perfectly fit the needs of conservative advancement suitable to C's most important niche(s). It may not take the form of a Rust-like "fat pointer". It may just be the ability to tell the compiler to enforce a particular constraint for relationships between specific struct fields/members (as someone else in this discussion suggested), in a backward-compatible manner such that the exact same code would compile in an older-standard compiler -- a very conservative approach that should, in fact, solve the problem as well as "fat pointers".
There are ways to get the actually important upgrades without recreating C++.
C++ doesn't have arrays which know their length.
I am not an expert at either C or Zig, so I would appreciate any feedback from anyone who can more intelligently compare the two.
What is needed is a category of actions where implementations (which I would call "conditionally-defined", where implementations would be required to indicate via "machine-readable" means [e.g. predefined macros, compiler intrinsics, etc.] all possible consequences (one of which would be UB), from which the implementation might choose in Unspecified fashion. If an implementation reports that it may process signed arithmetic using temporary values that may, at the compiler's leisure, be of an unspecified size that's larger than specified, but signed overflow will have no effect other than to yield values that may be larger than their type would normally be capable of holding, then the implementation would be required to behave in that fashion if integer overflow occurs.
In general, the most efficient code meeting application requirements could be generated by demanding semantics which are as loose as possible without increasing the amount of user code required to meet those requirements. Because different implementations are used for different purposes, so single set of behavioral guarantees would be optimal for all purposes. If compilers are allowed to reject code that demands guarantees an implementation doesn't support, then the choice of what guarantees to support could safely be treated as a Quality of Implementation issue, but the behavior of code that claims to support guarantees would be a conformance issue.
That doesn't particularly need modules -- just some form of
namespace foo {
}- In other words you've created a fantastic shoe-gun. One update line missed (either length or data, or data re-used outside the struct) and your "simple" struct is a huge headache, including potential security vulnerabilities.
- Re-implementing a common error prone thing is exactly what language improvements should target.
And having a special data-and-length type would make these guarantees... how? You're ultimately going to need to be able to create these objects from bare data and length somehow, so it's a case of garbage-in-garbage-out.
On a slightly more personal note: What are some undefined behaviors that you would like to turn into defined behavior, but can't change for whatever reasons that be?
Quoting http://blog.llvm.org/2011/05/what-every-c-programmer-should-...
> This behavior enables certain classes of optimizations that are important for some code. For example, knowing that INT_MAX+1 is undefined allows optimizing "X+1 > X" to "true". Knowing the multiplication "cannot" overflow (because doing so would be undefined) allows optimizing "X*2/2" to "X". While these may seem trivial, these sorts of things are commonly exposed by inlining and macro expansion. A more important optimization that this allows is for "<=" loops like this:
> for (i = 0; i <= N; ++i) { ... }
> In this loop, the compiler can assume that the loop will iterate exactly N+1 times if "i" is undefined on overflow, which allows a broad range of loop optimizations to kick in. On the other hand, if the variable is defined to wrap around on overflow, then the compiler must assume that the loop is possibly infinite (which happens if N is INT_MAX) - which then disables these important loop optimizations. This particularly affects 64-bit platforms since so much code uses "int" as induction variables.
The fact is that if the compiler encounters undefined behaviour, it can do basically whatever it wants and it will still be standard-compliant.
The worst thing is that people take it as acceptable that this loop is going to operate differently upon overflow (e.g. assume N is TYPE_MAX) depending on whether i or N are signed vs. unsigned.
I've gone a lifetime programming, and this kind of stuff never, ever matters one iota.
for (int i = 0; i < N; i += 2) {
//
}
Reasonably common idea but the compiler is allowed to assume the loop terminates precisely because signed overflow is undefined.I’m not trying to argue that signed overflow is the right tool for the job here for expressing ideas like “this loop will terminate”, but making signed overflow defined behavior will impact the performance of numerics libraries that are currently written in C.
From my personal experience, having numbers wrap around is not necessarily “better” than having the behavior undefined, and I’ve had to chase down all sorts of bugs with wraparound in the past. What I’d personally like is four different ways to use integers: wrap on overflow, undefined overflow, error on overflow, and saturating arithmetic. They all have their places and it’s unfortunate that it’s not really explicit which one you are using at a given site.
So it's not the best solution. If we want to make this behaviour for optimizations (that are to me not worthed, giving the risk of potentially critical bugs) we must make that behavior explicit, not implicit: thus is the programmer that has to say to the compiler, I guarantee you that this operation will never overflow, if it does it's my fault.
We can agree that having a number that wraps around is not a particularly good choice. But unless we convince Intel in some way that this is bad and make the CPU trap on an overflow, so we can catch that bug, this is the behaviour that we have because is the behaviour of the hardware.
The language is not a model of hardware, nor should it be. If you want to write to the hardware, the only option continues to be assembly.
This is exactly what every C programmer does, all the time.
Just to be sure I understand the fine details of this -- what would the impact be if the compiler assumed (correctly) that the loop might not terminate? What optimization would that prevent?
Loaded question—the compiler is absolutely correct here. There are two viewpoints where the compiler is correct. First, from the C standard perspective, the compiler implements the standard correctly. Second, if we have a real human look at this code and interpret the programmer’s “intent”, it is most reasonable to assume that overflow does not happen (or is not intentional).
The only case which fails is where N = INT_MAX. No other case invokes undefined behavior.
Here is an example you can compile for yourself to see the different optimizations which occur:
typedef int length;
int sum_diff(int *arr, length n) {
int sum = 0;
for (length i = 0; i < n; i++) {
sum += arr[2*i+1] - arr[2*i];
}
return sum;
}
At -O2, GCC 9.2 (the compiler I happened to use for testing) will use pointer arithmetic, compiling it as something like the following: int sum_diff(int *arr, length n) {
int sum = 0;
int *ptr = arr;
int *end = arr + n;
while (ptr < end) {
sum += ptr[1] - ptr[0];
ptr += 2;
}
return sum;
}
At -O3, GCC 9.2 will emit SSE instructions. You can see this yourself with Godbolt.Now, try replacing "int" with "unsigned". Neither of these optimizations happen any more. You get neither autovectorization nor pointer arithmetic. You get the original loop, compiled in the most dumb way possible.
I wouldn’t read into the exact example here too closely. It is true that you can often figure out a way to get the optimizations back and still use unsigned types. However, it is a bit easier if you work with signed types in the first place.
Speaking as someone who does some numerics work in C, there is something of a “black art” to getting good numerics performance. One easy trick is to switch to Fortran. No joke! Fortran is actually really good at this stuff. If you are going to stick with C, you want to figure out how to communicate to the compiler some facts about your program that are obvious to you, but not obvious to the compiler. This requires a combination of understanding the compiler builtins (like __builtin_assume_aligned, or __builtin_unreachable), knowledge of aliasing (like use of the "restrict" keyword), and knowledge of undefined behavior.
If you need good performance out of some tight inner loop, the easiest way to get there is to communicate to the compiler the “obvious” facts about the state of your program and check to see if the compiler did the right thing. If the compiler did the right thing, then you’re done, and you don’t need to use vector intrinsics, rewrite your code in a less readable way, or switch to assembly.
(Sometimes the compiler can’t do the right thing, so go ahead and use intrinsics or write assembly. But the compiler is pretty good and you can get it to do the right thing most of the time.)
It might seem like defining the semantics for signed overflow would be helpful but it turns out it's not, either from a security view or for efficiency. In general, defining the behavior in cases that commonly harbor bugs is not necessarily a good way to fix them.
Personally, I would like to get rid of many of the trap representations (e.g., for integers) because there is no existing hardware in many cases that supports them and it gives implementers the idea that uninitialized reads are undefined behavior.
On the other hand, I just wrote a proposal to WG14 to make zero-byte reallocations undefined behavior that was unanimously accepted for C2x.
Unsigned types have their own issues, though: they overflow at "small" values like -1, which means that doing things like correctly looping "backwards" over an array with an unsigned index is non-trivial.
> On the other hand, I just wrote a proposal to WG14 to make zero-byte reallocations undefined behavior that was unanimously accepted for C2x.
You're saying that realloc(foo, 0) will no longer free the pointer?
If people used them while parsing binary inputs that would prevent a lot of security bugs.
The fact that this question exists and is full of wrong answers suggests a language solution is needed: https://stackoverflow.com/questions/1815367/catch-and-comput...
http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2466.pdf
(signal is a strong word... maybe indicate?)
(Note that while `-ftrapv` would seem equivalent, I've found it to be less reliable, particularly with compile-time checking.)
if (FAILED(DWordMult(a, b, &product)))
{
// handle error
}I know there's recently been some movement towards standardizing something in this direction, but I don't know what the status of that work is. Probably one of the folks doing the AUA can update.
Your code assumes that negating a negative value is positive. Your division check forgot about INT_MIN / -1. Your signed integer average is wrong. You confused bitshift with division. etc. etc. etc.
Unsigned arithmetic is tractable and should be treated with caution. Signed arithmetic is terrifying and should be treated with the same PPE as raw pointers or `volatile`.
This applies if arithmetic maps to CPU instructions, but not to Python or Haskell or etc. If you have automatic bignums, signed arithmetic is of course better.
I presume you'd want signed overflow to have the usual 2's-complement wraparound behavior.
One problem with that is that a compiler (probably) couldn't warn about overflows that are actually errors.
For example:
int n = INT_MAX;
/* ... */
n++;
With integer overflow having undefined behavior, if the compiler can determine that the value of n is INT_MAX it can warn about the overflow. If it were defined to yield INT_MIN, then the compiler would have to assume that the wraparound was what the programmer intended.A compiler could have an option to warn about detected overflow/wraparound even if it's well defined. But really, how often do you want wraparound for signed types? In the code above, is there any sense in which INT_MIN is the "right" answer for any typical problem domain?
There is no answer different that INT_MIN that would be right and make sense, i.e. the natural properties of the + operator (associativity, commutativity) are respected. Thus, by want of another possibility, INT_MIN is precisely the right answer to your code.
I read your code and it seems to me very clear that INT_MIN is exactly what the programmer intended.
Well, I'm the author and that's not what I intended.
I used INT_MAX as the initial value because it was a simple example. Imagine a case where the value happens to be equal to INT_MAX, and then you add 1 to it.
The fact that no result other than INT_MIN makes sense doesn't imply that INT_MIN does make sense. Saturation (having INT_MAX + 1 yield INT_MAX) or reporting an error seem equally sensible. We don't know which behavior is "correct" without knowing anything about the problem domain and what the program is supposed to do.
A likely scenario is that the programmer didn't intend the computation to overflow at all, but the program encountered input that the programmer hadn't anticipated.
INT_MAX + 1 commonly yields INT_MIN because typical hardware happens to work that way. It's not particularly meaningful in mathematical terms.
As for "natural properties", it violates "n + 1 > n". C integers are not, and cannot be, mathematical integers (unless you can restrict values to the range they support).
Sometimes you're writing code where it really, really matters and you're more than willing to spend the extra cycles for every add/mul/etc. Having these new types as a portable idiom would help.
N2466 2020/02/09 Svoboda, Towards Integer Safety
http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2466.pdf
The committee asked the proposers for further work on this effort.
Integer types that saturate are an interesting idea. Because signed integer overflow is undefined behavior, implementations are not prohibited from implementing saturation or trapping on overflow.
The entire notion that "since this is undefined behavior it does not exist" is the biggest fallacy in modern compilers.
It's used by a lot of current software in Linux, notably systemd and glib2. It solves a major headache with C error handling elegantly. Most compilers already support it internally (since it's required by C++). It has predictable effects, and no impact on performance when not used. It cannot be implemented without help from the compiler.
int do_something(void) {
FILE *file1, *file2;
object_t *obj;
file1 = fopen("a_file", "w");
if (file1 == NULL) {
return -1;
}
defer(fclose, file1);
file2 = fopen("another_file", "w");
if (file2 == NULL) {
return -1;
}
defer(fclose, file2);
obj = malloc(sizeof(object_t));
if (obj == NULL) {
return -1;
}
// Operate on allocated resources
// Clean up everything
free(obj); // this could be deferred too, I suppose, for symmetry
return 0;
}Edit: Also please review how attribute cleanup is used by existing C code before jumping into proposals. If something is added to C2x which is inconsistent with what existing code is already doing widely, then it's no help to anyone.
#define DEFER(a, b, c) \
for (bool _flag = true; _flag; _flag = false) \
for (a; _flag && (b); c, _flag = false)
int fun() {
DEFER(FILE *f1 = fopen(...), (NULL != f1), mfclose(f1)) {
DEFER(FILE *f2 = fopen(...), (NULL != f2), mfclose(f2)) {
DEFER(FILE *f3 = fopen(...), (NULL != f3), mfclose(f3)) {
... do something ...
}
}
}
}
We are also looking at the attribute cleanup. Sounds like you should be involved in developing this proposal?That would allow us to write:
defer close(file);
or: defer {
release_hardware();
close(port);
}
I feel like that syntax fits very nicely with other parts of C, and could even potentially lend itself well to some very subtle/creative uses.I feel like a very C-like defer would:
- Trigger at the exit of the scope-level where it was declared.
- Be able to defer a single statement, or a scope-block.
- Be nestable, since a defer statement just runs its target
scope-block at the exit of the scope-block where it's defined.
- Run successive defer statements in LIFO order, allowing later
defer statements to still use resources that will be cleaned up
by the earlier ones.Also it's function-level (like golang) not scope-level (like attribute cleanup). As argued elsewhere in the this thread, golang got this wrong.
Also also, overwriting the return address on the stack kills internal CPU optimizations that both Intel and AMD do for branch prediction.
FWIW, I don't think it would wind up being spelled with attribute syntax because we would likely want programmers to have a guarantee that the cleanup will happen (and attributes can be ignored by the implementation).
#ifdef __STDC_CLEANUP__
#define my_cleanup(func) stdc_cleanup(func)
#else
#define my_cleanup(func) __attribute__((cleanup(func)))
#endif
i.e. it would require that it at least goes in the same places as an attribute.So I guess it needs someone to take that and update it, also to pull up a full list of current Linux software which is using this feature (which as I say these days is a surprising amount).
#define frr_with_privs(privs) \
for (struct zebra_privs_t *_once = NULL, \
*_privs __attribute__( \
(unused, cleanup(_zprivs_lower))) = \
_zprivs_raise(privs, __func__); \
_once == NULL; _once = (void *)1)
This gives us a block construct that guarantees elevated privileges are dropped when the block is done: frr_with_privs(privs) {
... whatever ...
break; /* exit block, drop privileges */
return; /* return, drop privileges */
}Safe strcpy
char *stecpy(char *d, const char *s, const char *e)
{
while (d < e && *s)
*d++ = *s++;
if (d < e)
*d = '\0';
return d;
}
main() {
char buf[64];
char *ptr, *end = buf+sizeof(buf) ;
ptr = stecpy(buf, "hello", end);
ptr = stecpy(ptr, " world", end);
}
Existing solutions are still error-prone, requiring continual recalculation of buffer len after each use in a long sequence, when the only thing that matters is where the buffer ends, which is effectively a constant across multiple calls.What are the chances of getting something like this added to the standard library?
There is the problem of detecting that the function overflows despite being a “safe” function. And there is the problem of precisely predicting what happens after the call, because there might be an undefined behavior in that part of the execution. When writing to, say, a member of a struct, you pass the address of the next member and the analyzer can safely assume that that member and the following ones are not modified. With a function that receives a length, the analyzer has to detect that if the pointer passed points 5 bytes before the end of the destination, the accompanying size it 5, if the pointer points 4 bytes before the end the accompanying size is 4, etc.
This is a much more difficult problem, and as soon as the analyzer fails to capture this information, it appears that the safe function a) might not be called safely and b) might overwrite the following members of the struct.
a) is a false positive, and b) generally implies tons of false positives in the remainder of the analysis.
(In this discussion I assume that you want to allow a call to a memory function to access several members of a struct. You can also choose to forbid this, but then you run into a different problem, which is that C programs do this on purpose more often than you'd think.)
Does anyone have insight on why?
*p += sprintf(*p, "hello");
*p += sprintf(*p, "world"); int size = snprintf(NULL,0,"some format string blah blah ...");
if (size < 0) error();
if (size == INT_MAX)
error(); // because we need one more byte to store the NUL byte
size++;
char *p = malloc(size);
if (p == NULL)
error();
int newsize = snprintf(p,size,"some format string blah blabh ... ");
if (newsize < 0) error();
if (newsize > size)
{
// ... um ... we still got truncated?
}
Yes, using NULL with `snprintf()` if the size is 0 is allowed by C99 (I just checked the spec).One thing I've noticed about the C standard library is that is seems adverse to functions allocating memory (outside of `malloc()`, `calloc()` and `realloc()`). I wonder if this has something to do with embedded systems?
It can also fail on bad format specifiers--not directly irrelevant here except that it forces snprintf to have a signed return value, and mixing signed (the return value) and unsigned (the size limit parameter) types is usually bad hygiene, especially in interfaces intended to obviate buffer overflows.
I'm new to C, in case you couldn't tell.
It's hard to appreciate what's going on at WG14 (or take part) when you can see the results only from afar, with none of the surrounding discussion.
I recently read Jens Gustedt's blog on C2x where he casually recommended this as a way to get involved: "The best is to get involved in the standard’s process by adhering to your national standards body, come to the WG14 meetings and/or subscribing to the committee’s mailing list."
Afaict (from browsing the wg14 site), the mailing list and its archives are not open to access.
https://webcache.googleusercontent.com/search?q=cache:TnEGL4...
EDIT: In general, how is one supposed to approach wg14 with ideas or need for clarification on the standard's wording / interpretation?
I'm currently working on an update to the committee website to clarify exactly this sort of thing! Unfortunately, the update is not live yet, but it should hopefully be up Soon™.
Currently, the approach for clarifications and ideas both require you to find someone on the committee to ask the question or champion your proposal for you. We hope to improve this process as part of this website update to make it easier for community collaboration.
Back in the '80s and '90s I was pretty good at C. I don't think there was anything about the language or the compilers than that I did not understand. I used C to write real time multitasking kernels for embedded systems, device drivers and kernel extensions for Unix, Windows, Mac, Netware, and OS/2. I did a Unix port from swapping hardware to paging hardware, rewriting the processes and memory subsystems. I tricked a friend into writing a C compiler. I could hold my own with the language lawyers on comp.lang.c.
Somewhere in there I started using C++, but only as a C with more flexible strings, constructors, destructors, and "for (int i = ...)", and later added STL containers to that.
Sometime in the 2000s, I ended up spending more and more time on smaller programs that were mostly processing text, and Perl became my main tool. Also I ended up spending a lot of helping out less experiences people at work who were doing things in PHP, or JavaScript, or Java. My C and C++ trickled to nothing.
I've occasionally looked at modern C++, but it is so different from what I was doing back in '90s or even early '00s I sometimes have to double check that I'm actually looking at C++ code.
Is modern C like that, or is it still at its core the same language I used to know well?
What might perhaps be more challenging is adjusting to the changes in compilers. They tend to optimize code more aggressively and so writing code that closely follows the rules of the language (rather than making assumptions about the underlying hardware, even valid ones) is more important today than it was back in the 80's.
I think the lack of powerful tools in 1990s-2000s contributed to the thought by some that C is 'diffcult' in terms of safety. However, things have moved on.
> Although the first edition of K&R described most of the rules that brought C's type structure to its present form, many programs written in the older, more relaxed style persisted, and so did compilers that tolerated it. To encourage people to pay more attention to the official language rules, to detect legal but suspicious constructions, and to help find interface mismatches undetectable with simple mechanisms for separate compilation, Steve Johnson adapted his pcc compiler to produce lint [Johnson 79b], which scanned a set of files and remarked on dubious constructions.
https://gforge.inria.fr/frs/download.php/latestfile/5298/Mod...
(Homepage: https://modernc.gforge.inria.fr/ )
A little effort and you could make C deprecated. ;-)
This makes me think that there are as many C++ gurus than Go(ogle) gurus who want to kill C to be the new Java which brings you a bad coffee from a dirty kitchen.
Why?
Consider the following code:
LetsReconsiderPriorities(n, A)
int n, A[n];
{
return A[n + 1];
}
main() {
static int A[1];
return LetsReconsiderPriorities(1, A);
}
Can anyone guess what clang/gcc complain about? They complain about K&R syntax, yet say nothing about the buffer overflow error. Thanks to modern arrays, the overflow can be said to clearly contradict the intentions of the program author. So why aren't compiler authors focusing on that? Rather than showing warnings that I'd say rightfully belong in lint? Note: Same is true with -Wall, [static n], and even [static 1]: compiler complains about language style and ignores real bugs.I would estimate that roughly 15% of the issues / pull requests that get filed against C language projects are due to these linter errors that accumulated in compilers over the years, based on a quick glance at STB. https://github.com/nothings/stb/issues?q=warning (29 + 132.) / (156 + 794) It's a big obstacle to sharing C code with others. It'd be great if the C Language Committee could ask compiler authors to remove all these distracting warnings like "unused parameter" now that we have amazing tools like runtime sanitizers that deliver real results.
Also, have we considered addressing the prototype problem with the freedom to choose an ILP64 data model instead? How much do prototypes honestly matter in that case? DSO ABI compatibility might be an issue for Linux distros, but it doesn't concern all of us. Also not terribly concerned about 64-bit type promo since 16-bit is usually what fast DSP wants, and the language today doesn't make that easy.
Lastly consider that C was designed at a research laboratory. If there's one thing researchers love to do, it's what I like to call "yolo coding" which is perfectly valid use case of getting experimental / prototyping code written in a way where one needn't care too much about language formalities and best practices. It'd be great if the standards committee acknowledged that as being a legitimate use case (similar to how "high level assembler" is explicitly acknowledged), because future revisions of the language should ideally maintain as much of the original intentions as possible. See also: https://www.lysator.liu.se/c/dmr-on-noalias.html (Note: I think dmr goes too far here, but interesting bit of history to think about, now that everything that isn't char is implicitly noalias!)
In other words, let us choose. Please don't force us.
Aside from understanding how the language itself has changed, maybe something else to put on the list is how to apply more modern programming practices in C.
In the 90s, I don't think I ever saw C code with unit tests. Any kind of automated testing was pretty rare. I've become convinced that testing in some form is a good thing. If I were going back to C, I'd want to understand the best way to go about that.
People also didn't care (or know) much about security back then. C has some obvious pitfalls (buffer overflows, etc.), and it is pretty important to know good ways to minimize risk. I'd want to understand best practices and techniques for this.
Also, back then build tools were very simple, and some of them were not my favorite things to use (Imake, I'm looking at you). Build tools have advanced a lot since then. Features like reliable, deterministic incremental builds exist now. Some things could be less tedious to configure and maintain. There are probably best practices and preferred choices in build tools, but what exactly they are is another thing I'd want to know.
These are probably not questions that necessarily need an answer from people whose expertise is the language itself, though, so I guess this is a tangent.
And there were plenty of security related papers and OSes from other companies like IBM, Xerox and DEC.
Some hints on what I'm referring to can be found here: https://github.com/mpv-player/mpv/commit/1e70e82baa9193f6f02...
Unrelated, but I also miss a binary constant notation (such as 0b10101)
0xDEADB_EEF
0b1_010_110111001001
etc.
(strchr is the most obvious, but in general most search/lookup type functions are like this...)
Add to clarify: the current prototype for strchr is
char *strchr(const char *s, int c);
Which just drops the "const", so you might end up writing to read-only memory without any warning. Ideally there'd be something like: maybe_const_out char *strchr(maybe_const_in char *s, int c);
So the return value gets const from the input argument. Maybe this can be done with _Generic? That kinda seems like the "cannonball at sparrows" approach though :/
(Also you'd need to change the official strchr() definition...)There are plenty of programing languages that distinguish strongly between mutable and immutable references, and that have the parametric polymorphism to let functions that can use both kinds return the same thing you passed to them, though. C will simply just never be one of them.
With that, selecting the correct function via `_Generic` should be possible (`_Generic` is a bit fiddly, but matching on `const char * ` and `char * ` should work just fine for this), and for the most part this is actually an/the intended use case for `_Generic` - it's basically the same as the type-generic math functions, more or less.
But making function signatures const-correct solves only a small part of the problem. A new API can only be used in new code, and casts can remove the constness from pointers leaving open the possibility that poorly written code will inadvertently change the const object. An attempt to change a global variable declared const will in all likelihood crash, but changing a local const can cause much more subtle bugs.
In my view, a more complete solution must include improving the detection of these types bugs in compilers and other static and even dynamic analyzers even without requiring code changes. It's not any more difficult to do that detecting out of bounds accesses. (In full generality it cannot be done just by relying on const; some other annotation is necessary to specify that a function that takes a const pointer doesn't cast the constness away and modify the object regardless.)
This, if one did:
char *strchr2(char return *restrict src, char target)
{
while(*src)
{
if (*src == target) return src;
src++;
}
}
then one version of the function could support both const and non-const usage.
BTW, I'd also like to see "register" and "return register" be usable as a qualifiers for pointer-type function parameters which would promise that the passed in pointer wouldn't "escape", or else that it could only escape through the return value (so a compiler that could see everything done with the return value wouldn't have to worry about the argument escaping).C++ solved this by overloading strchr():
const char *strchr(const char *s, int c);
char *strchr(*char *s, int c);
C of course doesn't have overloading.One solution could have been to define two functions with different names, perhaps "strchr" and "strcchr". The time to do that would have been 1989, when the original ANSI C standard was published.
I suppose a future C standard could leave strchr() as it is (necessary to avoid breaking existing code) and add two new functions.
component.h:
struct obj;
typedef struct obj obj_t;
obj_t *obj_create(void);
// .. the rest of the API
component.c: struct obj {
int status;
// .. whatever else
};
obj_t *
obj_create(void)
{
return calloc(1, sizeof(obj_t));
}
However, as the component grows in complexity, it often becomes necessary to separate out some of the functionality (in order to re-abstract and reduce the complexity) into a another file or files, which also operate on "struct obj". So, we move the structure into a header file under #ifdef __COMPONENT_PRIVATE (and/or component_impl.h) and sprinkle #define __COMPONENT_PRIVATE in the component source files. It's a poor man's "namespaces".Basically, this boils down to the lack namespaces/packages/modules in C. Are you aware of any existing compiler extensions (as a precedent or work in that direction) which could provide a better solution and, perhaps, one day end up in the C standard?
P.S. And if C will ever grow such feature, I really hope it will NOT be the C++ 'namespace' (amongst many other depressing things in C++). :)
What I can say while we are on the subject, is that I have seen C code (most often C code that started its life in the 1990s, to be fair) that instead of showing an abstract struct in the public interface, showed a different struct definition.
Please don't do this. Yes, when compiling nowadays, eventually every compilation unit ends up as object files passed to a linker that doesn't know about types, but this is undefined behavior. It makes it difficult to find undefined behavior in the rest of the code because there is a big undefined behavior right in the middle of it.
The thing I am describing is when you link a compilation unit using:
struct internal_state { int dummy; } state;
with another compilation unit that defined the same state differently: struct internal_state {
int actual_meaningful_member_1;
unsigned long actual_meaningful_member_2; } state;
As far as I know, BSD socked do not do this. Zlib was doing this (https://github.com/pascal-cuoq/zlib-fork/blob/a52f0241f72433... ), but I have had the privilege of discussing this with Mark Adler, and I think the no-longer-necessary hack was removed from Zlib.BSD sockets probably have a different kind of UB, related to so-call “strict aliasing” rules, unless they have been carefully audited and revised since the carefree times in which they were written. I am going to have to let you read this article for details (example st1, page 5): https://trust-in-soft.com/wp-content/uploads/2017/01/vmcai.p...
struct obj_impl {
// real members
...
};
In public API header:
struct obj {
unsigned char _private[N]; // -- where N is the size of obj_impl
};
I have seen such code too. It is also potentially error-prone. Certainly not advocating for it.You can spread components in as many object files or libraries as you wish.
IMHO it's not a C related problem but a code design one.
Write libraries (with headers) only if you need to share the code but if you're not sure about that just include it for your specific program.
There is no shame to include local files containing declarations and definitions.
I think it is a misconception from C programmers to write headers for local purpose.
2. Is there, or was there ever a proposal to make struct types without a tag be structurally typed? This would not break backwards compatibility as far as I can see, and would make these types much more useful as ad-hoc bags of data. Small example:
struct {size_t size; void *data;} data = get_data();
int hash = hash_data(data);
I believe there was at least one proposal about error handling that more or less relied on the above to be valid semantically.3. Is there any interest in making the variadic function interface a bit nicer to use? I would like to bring back an old feature and have an intrinsic to extract a pointer from the variadic parameter list, so that we can iterate over it ourselves (or even index directly).
void *arg_ptr = va_ptr(last);
More out there would be a parameter that would be implicitly passed to a variadic function to indicate the number of arguments. void variadic(..., va_size count) {
}
variadic(10, 20, 30); // count would be three1. I want this too.
2. Here is my proposal: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2366.pdf
3. Yes, variadic functions should be improved.
I think the authors of C89 most likely thought that principle was sufficiently obvious that there was no need to expressly state it. Were it not for the Standard's rule forbidding it, an implementation might plausibly have ignored the possibility of an `int` being accessed via an `unsigned`, but I don't think the authors of the Standard imagined that a non-obtuse compiler writer wouldn't allow for the possibility that something like:
void inc_float_bits(float *f)
{
((unsigned*)f)+=1;
}
might affect the stored value of a `float`.The present rules, as written, have absurd corner cases. Given something like:
union U { float f[2]; unsigned ui[2]; } uu;
the Standard would, so far as I can tell, treat as identical the functions test1, test2, and test3 below: float test1(int i, int j)
{
uu.f[i] = 1.0f;
uu.ui[j] += 1;
return uu.f[i];
}
float test2(int i, int j)
{
*(uu.f+i) = 1.0f;
*(uu.ui+j) += 1;
return *(uu.f+i);
}
float evil(unsigned *ui, float *f)
{ *f = 1.0f; *ui += 1; return *f; }
int test2(int i, int j)
{
evil(uu.f+i, uu.ui+j);
}
If a dereferenced pointer to union member type isn't allowed to access the union, the first example would be UB regardless of i and j, but that would imply that non-character arrays within unions are meaningless. If such pointers are allowed to access union objects, then test2 (and the evil function within it) would have defined behavior even when i and j are both zero.BTW, I think any quality compiler should recognize the possiblity of type punning in the first two, though the Standard doesn't actually require either. Neither clang or gcc, however, recognizes the possibility of type punning in the second even though the behavior of the [] operators in the first are
defined* as equivalent to the second.(The committee is fine with incremental improvements, but new syntax need to have strong motivation behind it, much stronger than this.)
That being said, I would like it if the default types for variadic functions were promoted from int/float to int64_t/double in order to be more reflective of the wider ranges supported by these types.
1. define a highly-extensible abstraction model, which implementations intended for various purposes should be expected to extend to suit those purpose, or
2. define an abstraction model which is sufficiently complete that programs can do everything that would need to be done, without need for extensions?
Reading the C89 and C99 Rationale documents, it's clear that those standards were intended to meet the former purpose. The way some compilers treat "Undefined Behavior", however, suggests that the maintainers view the Standard as aimed toward the latter purpose.
During the 1980s and 1990s, it was generally cheaper and easier for implementations to extend the Standard's abstraction model by specifying that many actions would be processed "in a documented fashion characteristic of the environment" than it would have been to do anything else, so there was no need to worry about whether the Standard allowed programmers to specify when such behavior was required. That no longer holds true, however.
While it would be reasonable to deprecate code which relies upon such treatment without explicitly demanding it, such deprecation would only make sense if there were a means of demanding such treatment when required. For the Committee to provide such means, however, it would have to reach a consensus as to the purposes for which the Standard's abstraction model is meant to be suitable. Are you aware of any such consensus?
I would like to see the Standard either rewritten in such a way as to actually define (sometimes as optional features) everything necessary to make an implementation suitable for a wide range of tasks, or else expressly state that, e.g. "There are some circumstances where the behavior of some action would documented by parts of the Standard, the documentation of the implementation and execution environment, or other materials, but some other portions of the Standard would characterize those actions as invoking Undefined Behavior. This Standard expressly waives jurisdiction in such cases so as to allow implementations designed for a variety of purposes to process them in whatever fashion would best suit those purposes."
What would you think about including something like those last two sentences in the Standard, so as to help clarify its intention?
Joining the committee requires you to be a member of your country's national body group (in the US, that's INCITS) and attend at least some percentage of the official committee meetings, and that's about it. So membership is not difficult, but it can be expensive. Many committee members are sponsored by their employers for this reason, but there's no requirement that you represent a company.
I joined the committees because I have a personal desire to reduce the amount of time it takes developers to find the bugs in their code, and one great way to reduce that is to design features to make harder to write the bugs in the first place, or to turn unbounded undefined behavior into something more manageable. Others join because they have specific features they want to see adopted or want to lend their domain expertise in some area to the committee.
I followed the article which attempted to interpret the C standard and come to a conclusion. The conclusion is:
> The takeaway message is that pointer arithmetic is only defined for pointers pointing into array objects or one past the last element. Comparing pointers for equality is defined if both pointers are derived from the same (multidimensional) array object. Thus, if two pointers point to different array objects, then these array objects must be subaggregates of the same multidimensional array object in order to compare them. Otherwise this leads to undefined behavior.
Based on the above, I arrived at the conclusion after reading this that comparing two distinct malloc()'d pointers for equality itself is undefined behaviour since malloc() is likely to return pointers to distinct objects that are not part of a sub-aggregate object.
I know this is incorrect, but I don't know why I'm wrong.
[1]: https://stefansf.de/post/pointers-are-more-abstract-than-you...
&a + 1 == &b is unspecified: it may produce 0 or 1, and it may not produce the same result if you evaluate it several times.
Similarly, if both the char pointers p and q were obtained with malloc(10), after they have been tested for NULL, all these operations are valid:
p == q (false)
p + 1 == q (false)
p + 1 == q + 1 (false)
p + 10 == q + 1 (false)
Only p+10 == q and p == q+10 are unspecified (of the comparisons that can be built without invoking UB during the pointer arithmetic itself).I have no idea what led that person to (apparently) write that &a==&b is undefined. This is plain wrong. I do not see any ambiguity in the relevant clause (https://port70.net/~nsz/c/c11/n1570.html#6.5.9p6 ). Yes, the standard is in English and natural languages are ambiguous, but you might as well claim that a+b is undefined because the standard does not define what the word “sum” means (https://port70.net/~nsz/c/c11/n1570.html#6.5.6p5 ).
Write a function c that compares pointers in a compilation unit, and in another compilation using, define:
int a, b;
X1 = (&a == &b + 1);
X2 = c(&a, &b + 1);
The compiler can optimize the computation of X1 on the basis that comparing an offset of &a to an offset of &b will always: - be false
- or invoke undefined behavior
- or be unspecified
But the optimization will not apply to the computation of X2, so the two variables X1 and X2 can receive different values when you execute this example, although they appear to compute the same thing.Relational operators (< <= > >=) on pointers have undefined behavior unless both pointers point to elements of the same array object or just past the end of it. A single non-array object is treated as a 1-element array for this purpose.
(That's for object pointers. Function pointers can be compared for equality, but relational operators on function pointers are invalid.)
unsigned int x;
x -= x;
There's a lengthy StackOverflow thread where various C language-lawyers disagree on what the spec has to say about trap values, and under what circumstances reading an uninitialised variable causes UB. I'd appreciate an authoritative answer. Thanks for dropping by on HN!Could you expand on this?
There's some debate about the effects of reading an uninitialized local variable of unsigned char (like whether the same value must be read each time, or whether it's okay for each read to yield a different value).
This special exemption doesn't extend to any other types, regardless of whether or not they have padding bits or trap representations that could cause the read to trap. Few types do, yet the behavior of uninitialized reads in existing implementations is demonstrably undefined (inconsistent or contradictory to invariants expressed in the code of a test case), so any subtleties one might derive from the text of the standard must be viewed in that light.
> Except for the special case of unsigned char,
The SO article makes the bizarre claim that because
(1) an unsigned char, per the standard, cannot have any padding bits, it therefore cannot have a trap representation. And
(2) if it cannot have a trap representation, the use of an uninitialized value isn't undefined.
I'm willing to buy (1) but I don't remember (2) being required for UB. I think (2) is the step that is harder to follow intuitively. Admittedly, I have not read that part of the standard closely in some time.
You could argue that it suddenly becomes less UB if you take the address of x:
unsigned int x;
&x;
x -= x;
I'm not sure if this will add anything to the discussion on SO, but if you allow programs to do this, then after applying modern optimizing C compilers, you may end with multiplications by 2 that produce odd results, or uninitialized char variables that contain 500: http://blog.frama-c.com/index.php?post/2013/03/13/indetermin...So the short answer is that, for all intent and purposes, you should consider use of uninitialized variables as UB, because C compilers already do. (There exists somewhere a document clarifying what C compilers can and cannot do with indeterminate values. A search for “wobbly values” might turn it up. Anyway, you do not want to have wobbly values in your C programs any more than you want it to have undefined behavior.)
* Under C90, reading an uninitialized local was explicitly listed as UB.
* Under C99, if you weren't using a character type, it was still essentially UB, by way of trap values. (I don't think the particulars of the target hardware platform are relevant.)
* C11 reintroduced UB even for some cases involving character types. We were already invoking UB under C99, so we know we're still invoking UB under C11.
> You could argue that it suddenly becomes less UB if you take the address of x
I don't think so. As we're not using a character type, I don't think taking its address would change anything. This aligns with what msebor said.
Lastly, from the article:
> No, GCC is still acting as if j *= 2; was undefined.
I think GCC's behaviour is legal here. The target platform may have no trap values, but I don't see that GCC is prohibited from behaving as if there are. It would be legal (albeit bizarre) for it to generate code for a completely different ISA, and to bundle an emulator. If the spec says you've opened the door to UB, then unless your compiler documentation says otherwise, it's permitted to generate code that goes haywire, no?https://www.digitalmars.com/articles/C-biggest-mistake.html
I.e. offering a way that arrays won't automatically decay to pointers when passed as a function parameter.
*(aFoo+3) should work fine and return the 4th int in the array.Your proposal replaces my use of an array with two things, a pointer (as before) and a length. This is not too helpful, because I already could have done that if I'd wanted to.
What is missing is the ability to pass an array. Sometimes I want to toss a few megabytes on the stack. Don't stop me. I should be able to do that. The called function then has a copy of the original array that it can modify without mangling the original array in the caller.
C doesn't have a reasonable way of doing that. I know my proposal works, because we've been using it in D for 20 years.
Note that C is a pass-by-value language, so passing an array means that the called function can modify the content without the modifications being seen in the caller.
To sort of pass arrays in an ABI-compatible way, the version for older code would require putting the array inside a struct.
Even that doesn't fully work with any ABI that I've ever heard of. The struct doesn't really get passed. Disassemble the code if you have doubts. The caller allocates space for the struct, copies the struct there, and then passes a pointer to the struct. From the high-level view of the language, this is passing the struct, but the low level details are actually wrong.
The committee works a lot lobbyist. A minority of people with a large financial interest in the technology (such as compiler writers) have undue influence because they participate in the process. I always encourage C language users to take a more active role, but they usually don't. Cisco is an example of user community that actively takes part in C Standardization.
I hope that this perceived lack of enthusiasm means I am handling the conflict of interest honorably.
Is this enough to answer your question? I can look up the names of the people that were involved and communicate them privately if you are further interested.
Someone who read the LLVM mailing-list attentively should have seen it and may have a link.
https://news.ycombinator.com/item?id=22868999
I hope someone will provide the next link.
struct foo { int a; void *p; };
struct foo f = {0}; // legal C, f->p initialized like a static variable
struct foo f = {}; // not legal but supported by gcc
To me it would make sense that there is no need to specify a value for any of the members that are intended to be initialized exactly like static variables (and the first member is not special so I shouldn't have to explicitly assign a zero?). However the syntax currently demands at least one initializer.--
2. I recall seeing a proposal for allowing declarations after case labels:
switch (foo) {
case 1:
int var;
// ...
}
This is currently not allowed and you'd have to wrap the lines after case in braces, or insert a semicolon after the case label. Is this making it to c2x?--
3. I've run into some recent controversy w.r.t. having multiple functions called main (and this has come up in production code). In particular, I ran into a program programs that has a static main() function (with parameters that are not void or int and char[]), which is not intended to be the* main function that is the program's entry point.
gcc warns about this because the parameters disagree with what's prescribed for the program entry point. It's not clear to me whether this is intended to be legal or not.
--
4. Looking at the requirements for main brings up another question: it says how main should be defined (no static or extern keyword). However, the definition could be preceded by a static declaration, which then affects the definition that follows:
If the declaration of an identifier for a function has no storage-class specifier, its linkage is determined exactly as if it were declared with the storage-class specifier extern.
For an identifier declared with the storage-class specifier extern in a scope in which a prior declaration of that identifier is visible, if the prior declaration specifies internal or external linkage, the linkage of the identifier at the later declaration is the same as the linkage specified at the prior declaration.
Therefore, it is possible to have a main function with internal linkage and a definition that exactly matches the one given in the spec:
static int main(int, char *[]);
int main(int argc, char *argv[]) { /* ... */ }
As one might guess, this program doesn't make it through the linker when compiled with gcc. Is this supposed to be legal? Should the spec perhaps require main to have external linkage, and then allow other functions called main with internal linkage (and parameters that do not match what is required of the external one)?EDIT: ---
Are the fixes w.r.t. reserved identifiers going to make it in c2x? Can I finally have a function called toilet() without undefined behavior?
Unsigned arithmetic never overflows, and guarantees two's-complement behavior, because unsigned arithmetic is always carried out modulo 2^n:
> A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type. (6.2.5, Types)
Doing the computation in unsigned always does the "right thing"; the thing that one needs to be careful of with this approach is the conversion of the final result back to the desired signed type (which is very easy to get subtly wrong).
For unsigned operations the carry flag is used, and for signed operations, the overflow flag is used.
One is that unsigned arithmetic can overflow, and the behavior on overflow is defined to wrap around.
Another is to say that unsigned arithmetic cannot overflow because the result wraps around.
Both correctly describe the way it works; they just use the word "overflow" in different ways.
The C standard chooses the second way of describing it.
> Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type (6.3.1.3 Signed and unsigned integers)
Unsigned to signed is the hard direction. If the result would be positive (i.e. in range for the signed type), then it just works, but if it would be negative, the result is implementation-defined (but note: not undefined). You can further work around this with various constructs that are ugly and verbose, but fully defined and compilers are able to optimize away. For example, `x <= INT_MAX ? (int)x : (int)(x + INT_MIN) + INT_MIN` works if int has a twos-complement representation (finally guaranteed in C2x, and already guaranteed well before then for the intN_t types), and is optimized away entirely by most compilers.
I think most people colloquially call going A + 1 = B where B < A an overflow. Interesting. I knew they're different things, but never really thought about my word choice.
struct foo {
enum { t_char, t_int, t_ptr, /* .. */ } type;
int count;
union {
char c[];
int i[];
void *p[];
/* .. */
};
};
This isn't allowed, since flexible array members are only allowed in structs (but the union here is exactly where you'd put a flexible array member if you had only one type to deal with).Furthermore, you can't work around this by wrapping the union's members in a struct because they must have more than one named member:
struct foo {
enum { t_char, t_int, t_ptr } type;
int count;
union { /* not allowed! */
struct { char c[]; };
struct { int i[]; };
struct { void *p[]; };
};
};
But it's all fine if we either add a useless dummy variable or move some prior member (such as count) into these structs: struct foo {
enum { t_char, t_int, t_ptr } type;
int count;
union { /* this works but is silly and redundant */
struct { int dumb1; char c[]; };
struct { int dumb2; int i[]; };
struct { int dumb3; void *p[]; };
};
};
Of course, you could have the last member be union { char c; int i; void *p; } u[];
but then each element of u is as large as the largest possible member which is wasteful, and u can't be passed to any function that expects to get a normal, tightly packed array of one specific type.The GoLang defer statement defers the execution of a function until the surrounding function returns. The deferred call's arguments are evaluated immediately, but the function call is not executed until the surrounding function returns. It looks like an interesting mechanism for cleaning up resources.
For me "defer" only makes sense in the context of exceptions, basically as an equivalent to "finally". This is a slippery slope though, since golang's exceptions are, for a reason, rudimentary.
Would the proposed defer statement apply to loops as well? How would one implement such defers without dynamic allocation?
For example, if all past, current and contemplated hardware behaves in the same way, I assume that the standard will simply enshrine this behavior.
However, what if 99% of hardware behaves one way and 1% another? Do you set the behavior to "undefined" to accommodate the 1%? At what point to you decide that the minority is too small and you'll enshrine the majority behavior even though it disadvantages minority hardware?
---
[1] Famous examples include things like bit shift and integer overflow behavior.
We have dropped support for sign and magnitude and one's complement architectures from C2x (a decision Doug Gwyn does not agree with). There was some concern that Unisys may still use a one's complement architecture, but that this may only be in emulation nowadays.
- signed integer overflow or division by zero occurs, a division instruction traps on x86, while it silently produces an undefined result on PowerPC - left-shifting a 32-bit one by 32 bits yields 0 on ARM and PowerPC, but 1 on x86; - left-shifting a 32-bit one by 64 bits yields 0 on ARM, but 1 on x86 and PowerPC
So x86 actually has both behaviors in one box (three behaviors if you could the 32-bit and 64-bit scalar things you mentioned separately).
This is an example of where UB for simple operations actually helps even on a single hardware platform: it allows efficient vectorization.
My question was more about when behavior is being defined for the first time, which admittedly doesn't happen that often (but it could apply e.g., when thing fixed-width integer types, uintX_t and friends were introduced).
I have a love-hate relationship with C - I like it for small projects, but anything serious I really need to write it in a more safe language. I think GCC has some flags that can help, and I've been using tools like splint, but something baked into the standard would be amazing.
I guess what I mean by that is a language that has Rust's hyperactive, strongly opinionated compiler, borrow checker, no NULL, immutable by default, etc, but in a language that is no more syntactically ambitious that C89. I would be way more into a language like that than Rust.
A language that sort of feels like Go, but can actually be used for low-level systems programming.
On another note:
- Official support for __attribute__
- void pointers should offset the same size as char pointers.
- typeof (can't stress this one enough)
- __VA_OPT__
- inline assembly
- range designated initializer for arrays
- some GCC/Clang builtins
- for-loop once (Same as for loop, but doesn't loop)
Finally, stop putting C++ craps into C.
I know some people are against metaprogramming because they believe the abstractions hide the intrinsic of how the underlying code will execute, but I would love to write substantial tests in C without relying on FFI to Python or C++ to perform property-based testing, complex fuzzing, and whatever. I feel metaprogramming would be a huge boon for C tooling and developer productivity.
The former is compiler dependent and you cannot know how it's implemented. The former is simple text substitution and you're the one implementing it. I often find myself creating small embedded languages in CPP for making abstraction, and I know exactly what C code it's going to generate and thus the penalty if there's any.
People that are afraid of the preprocessor simply don't understand how powerful it's in good hands.
The background (I know Doug knows this): isdigit() takes an argument of type int, which is required to be either within the range of unsigned char, or have the value EOF (required to be negative, typically -1).
The problem: plain char is often signed, typically with a range of -128..+127. You might have a negative char value in a string -- but passing any negative value other than EOF to isdigit() has undefined behavior. Thus to use isdigit() safely on arbitrary data, you have to cast the argument to unsigned char:
if (isdigit((unsigned char)s[i])) ...
A lot of C programmers aren't aware of this and will pass arbitrary char values to isdigit() and friends -- which works fine most of the time, but risks going kaboom.Changing this could raise issues if -1 is a valid character value and also the value of EOF, but practically speaking -1 or 0xff will almost never be a digit in any real-world character set. (It's ÿ in Unicode and Latin-1, which might cause problems for islower and isalnum.)
FWIW, just looked at the man page (macos) and iswdigit() and isnumber() are mentioned.
How does the committee view non-portable existing code generally when considering changes?
In other words, will the C standard be effectively “done” at some time in the future?
Reviewing proposals to incorporate features supported by common implementations is another.
Aligning with other standards (e.g., floating point) and improving compatibility with others (C++) is yet another.
In general, when an ISO standard is done it essentially becomes dead. So for the C standard to continue to be active (on ISO's books) it needs to evolve.
I see the classic path of any programming language -- regardless of standardization -- is to continuously add features until it's too big and complex that nobody wants to deal with it any more. Then it's replaced by a newer, simpler language that takes the important bits and drops the unnecessary complexities. At that point, everybody sees that the older language was barking up the wrong tree, and they stop wasting time on it.
It's not the cessation of language change that causes language death -- that's merely a symptom. You can't keep a language alive simply by changing it every year. Some people sure have tried.
Alternatively, until it's evolved so much that there is so much diversity of implementation that simply knowing a library is written in "language X" doesn't tell me much about how it's written, or whether I can use it in my program which is also written in "language X".
Then again, C is the exception to every rule, so maybe we can keep piling on features indefinitely, and people will have to use it (even if they don't like it), for the same reason they started using it decades ago (even if we didn't like it).
http://www.open-std.org/jtc1/sc22/wg14/www/wg14_document_log...
These papers are usually quite interesting.
I appreciate the original simplicity of K & R, "The C Programming Language", 2nd Edition, and the relatively simple semantics of ANSI C89/ISO C90 compared to C99 and later.
You don't need complex parsing methods for ANSI C89/ISO C90 and you do not need the "lexer hack" to handle the typedef-name versus other "ordinary identifier" ambiguity.
A surprising number of colleges still teach K & R 2nd Edition C.
Whenever someone brags about using recursive-descent parsing methods, I always ask, are they using predictive, top-down parsing, or back-tracking?
I hope C never loses sight of it's roots nor morphs into C++ under the guise of creating a common subset, but which is really a disguised superset of C and C++
Please prevent the ever increasing demand for new features from overwhelming C's simplicity so it can no longer be parsed with simple methods.
Right now it's just scary to start a new project in C. It would be really great if there was more emphasis on correctness of the produced code instead of the insane optimizations.
If you are concerned about safety there are ways to achieve that, like using MISRA C, formally verifying your C, or by writing another language like Rust.
For example,
int buffer_len(struct buffer *buf) {
return buf->end - buf->start;
}
There are at least three states that trigger undefined behavior: buf is not a valid pointer, buf->end - buf->start doesn’t fit in int, and buf->end and buf->start don't point to the same object.I’m not sure how you would annotate this. At the function call site, you would somehow need to show that buf is a valid pointer, and that start/end point to same object and the difference fits in an int. It would start looking more like Coq or Agda than C.
Honestly, I think if you really want this kind of safety, your options are to use formal methods or switch to a different language.
There’s also this weird assumption here that the compiler detects undefined behavior in your program and then mangles it. It’s really the opposite—the compiler assumes that there is no undefined behavior in your program, and optimizes accordingly. In practice you can turn optimizations off and get something much closer to the “machine model” of C (which doesn’t really exist anyway) but most people hate it because their code is too slow.
Could you please provide an example of this?
int add(int a, int b) { return a + b; }
Unless the compiler can prove that `add` is never called with a and b values resulting in an overflow, this code can lead to UB, and, under your rules, the compilation aborts.Thankfully, there are a lot of tools to help developers catch UB these days (UBSan, static analyzers, valgrind, etc). I would recommend using those tools whenever starting a new project in C (or C++, for that matter).
int i;
[…]
i += 1;
potentially is undefined behavior; i could overflow.Compilers nowadays are fairly good at warning about definite undefined behavior.
I don’t think anybody would be happy with a compiler that aborted on all potential undefined behavior. That would (almost) be equivalent to banning the use of all signed ints.
Adding a rule requiring implementations to error out in cases of undefined behavior would be hard to specify in the standard. It could (and in my view should) be done by providing non-normative encouragement as "Recommended Practice."
Do you also answer questions about the standard libraries? This is not so much a C question as a library question:
I'm wondering if Apple's Grand Central Dispatch ever made it into a more integrated role in C's libraries, or if it will forever remain an outside add-on. And whether there is anything else at that level (level in the sense of high versus low level) in the standard libraries that plays such a role, that I should read up on instead of GCD.
We're remaining active while there are still people asking questions, so the west coast folks should hopefully have the chance to ask what they'd like.
> Do you also answer questions about the standard libraries?
Sure!
> I'm wondering if Apple's Grand Central Dispatch ever made it into a more integrated role in C's libraries, or if it will forever remain an outside add-on.
GCD has not been adopted into C yet, and I don't believe it's even been proposed to do so by anyone (or an alternative to GCD, either).
It would be an interesting proposal to see fleshed out for the committee, and there is a lot of implementation experience with the feature, so I think the committee would consider it more carefully than an inventive proposal with no real-world field experience.
Practically every second C codebase on earth has their own implementations of these at some point, and it remains a huge problem for e.g. writers of libraries, where you don't know how/where your library will be used.
On the third point, I have trouble thinking of any technical objections to such proposal.
This is useful for parallel computations, optimizations and readability, e.g.
sum += f(2);
sum += f(2);
can be optimized to x = f(2);
sum += x;
sum += x;
Would the current motto of the consortium forbid adding a feature such as marking a function as pure, that would not just promise, but also enforce that no side effects are caused (only local reads/writes, only pure functions may be called), and no inputs except for the function arguments are used?Suppose I want to add some debug tracing into f():
f.c: 42: f entered
f:c: 43: returning 2
that's a side effect, right? But now the pure attribute tells a lie. Never mind though; I don't care that some calls to f are "wrongly" optimized away; I want the tracing for the ones that aren't.In C++ there are similar situations involving temporary objects: there is a freedom to elide temporary objects even if the constructors and destructors have effects.
Even a perfectly pure function can have a side effect, namely this one: triggering a debugger to stop on a breakpoint set in that function!
If a call to f(2) is elided from some code, then that code will no longer hit the breakpoint set on f.
Side effect is all P.O.V. based: to declare something to be effect-free in a conventional digital machine, you have to first categorize certain effects as not counting.
The notion that "Undefined Behavior" is good for optimization is misguided and dangerous. What is good for optimization is having semantics that are loose enough to give the compiler flexibility in how it processes things, but tight enough to meet application requirements.
Instead of saying that compilers can do anything they want when their assumptions are violated, it would be far more useful to recognize what they are allowed to do on the basis of certain assumptions. For example, given a piece of code:
long long test1(long long x, int mode)
{
while(x)
x = slow_function_no_side_effects(x);
return x;
}
void long test2(long long x, int mode)
{
x = test1(x);
if (!mode)
x=0;
doSomething(x);
}
It would generally be useful and safe to allow a compiler that determines that no individual action performed by "test1()" could have any side effects may omit the call to "test1()" if its value never ends up being used, without having to prove that the slow function with no side effects will eventually return zero. It is likewise useful and safe to say that if the generated code observes either that the loop exits or that "mode" is zero, it may replace the call "doSomething(x)" with "doSomething(0)". The fact that both optimizations would be safe and useful individually, however, does not imply that it would be safe and useful to allow compilers to change the code for "test2()" so that it calls "doSomething(0)" or otherwise allow code to observe that the value of "x" is zero when mode is non-zero, without regard for whether "test1()" would complete.https://news.ycombinator.com/user?id=supercat
?
If you contact the HN gods maybe there is a way to recover access to that account.
Also, the problem with eliding breakpoints already exists afaik, since the compilers already check for pure functions.
There is at least one incorrect optimization present in Clang because of this (function that has no side-effects detected as pure, and call to that function omitted from a caller on this basis, when in fact the function may not terminate).
And you now have all the details of the Clang bug, by the way: write an infinite loop without side-effects in a C function, then call the function from another C function, without using its result.
If you were enforcing this with the compiler, you would also need something that would suppress the enforcing, because the millions of pre-existing functions would probably not get an updated attribute marking it as pure. And once you do that, the compiler can't really trust anything that function does, because it may actually be calling a non-pure function.
My job at NCC Group involves a lot of code reviews, so frequently the files that are of interest to me are the ones that contain the most defects. I typically identify these by compiling with compiler warnings turned up and warning suppression turned down. I'll frequently also make use of static and dynamic analysis, including the GCC and Clang sanitizers.
exctags --exclude=TAGS --exclude=TAGS.NEW --append -R -f TAGS.NEW --sort=yes && mv TAGS.NEW TAGS
My editor (vim) has native support for quickly jumping from a use to definition via this TAGS index. History is preserved (i.e., there is a "back" button), so you can quickly dive through 5 layers of API and back out to understand where a value went. It is quite useful for starting with what you know and following it to the surprising behavior, without executing the code.Conceptually, something must indicate to the function how many arguments it is supposed to request next, and with what types. Yes, you could write a function where this information is passed through a static-lifetime variable, but in practice the first mandatory argument is almost always used for that anyway.
2. I think many compilers already do this, but can the static initialization rules be relaxed a bit?
static const int a = 0;
static const int b = a; /* This is not standard C afaik. */
Thank you,
CodeandCI'd also say there is consensus that (2) would be beneficial. There are some good ideas in http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2067.pdf although I don't think repurposing the register keyword for it was very popular. Not just because it wouldn't be compatible with C++ which deprecated register some time ago, but also because it's novel with no implementation or user experience behind it. My impression that this is waiting for a new proposal.
N2353 2019/03/17 Sebor, Add strdup and strndup to C2X
N2352 2019/03/17 Sebor, Add stpcpy, and stpncpy to C2X
N2351 2019/03/17 Sebor, Add strnlen to C2X
He is lurking on this thread as well. These proposals can all be found in the document log at http://www.open-std.org/jtc1/sc22/wg14/www/wg14_document_log...6.33 Sebor, Add strnlen to C2X [N 2351] Result: No consensus on putting N2351 into C2X.
6.34 Sebor, Add stpcpy, and stpncpy to C2X [N 2352] Result: No consensus to put N2352 into C2X.
6.35 Sebor, Add strdup and strndup to C2X [N 2353] Result: N2353 be put into C2X. The committee wants a proposal for the wide character versions of any POSIX functions voted in this meeting.
Err... I thought Annex K is deprecated and dead? Whereas strl* seem very much alive, some compilers even give a "strcpy/strncpy is unsafe, use strlcpy instead" warning.
IMO they're a lot more ergonomic than the Annex K functions, and do the thing most programmers think the strncat/strncpy functions do (admittedly, not part of ISO C).
Annex K should be forgotten as the mistake it is and we can move on with existing real-world interfaces instead of inventing features from whole-cloth. I thought that was generally the C standard operating practice.
How can one process unicode (UTF-8) properly in C? As a CJK person, I wish there was a robust solution. Are there any standardized ways or proposals? (Using wchar doesn't count.)
I recommend heading toward a future where only UTF-8 encoding is used for multibyte characters and UCS-2 or similar for wchar_t. There is no need to support several different encodings.
N2198 2018/01/02 Ballman, Adding the u8 character prefix
I'm of the opinion that wchar_t should become an alias for char32_t.
Basically store the text as char arrays, and convert them when needed. Meanwhile, you could use this single file header: https://github.com/RandyGaul/cute_headers/blob/master/cute_u...
However, the book only describes the available standard functions, so even doing better than other manuals, everything it has to say on this subject fits in one chapter and feel underpowered.
Here are examples of working with unicode in C: https://begriffs.com/posts/2019-05-23-unicode-icu.html
Or incorporating features from this 14 item list? https://blog.regehr.org/archives/1180
As it appears these have failed: https://blog.regehr.org/archives/1287
Making C friendlier is always a good idea, and I think the committee is (slowly) working towards this goal. I would have to examine these papers by John Regehr in more detail. Looking quickly at his proposals I can see why there he couldn't find consensus for these ideas as some of them do appear controversial.
An example of a friendly dialect of C is always is C0 (C-naught) from CMU. I don't think I'm exaggerating when I say that this language has not "caught on".
int test(int a, int b)
{
int c = a/b;
if (f1())
f2(a,b,c);
}
Should a compiler be required to compute c before calling f1, and thus have to store the value of c across the function call?Better would be to define a set of semantics for loosely-sequenced traps, along with "causality barriers" to ensure that they only occur at tolerable times.
1. Will the Apple's Blocks extension, which allows creation of Closures and Lambda functions, be included in C2X?
2. Are there any plans to improve the _Generic interface (to make it easy to switch on multiple arguements, etc.)?
We haven't seen a proposal to add them to C2x, yet. However, there has been some interest within the committee regarding the idea, so I think such a proposal could have some support.
> 2. Are there any plans to improve the _Generic interface (to make it easy to switch on multiple arguements, etc.)?
I haven't seen any such plans, but there is some awareness that _Generic can be hard to use, especially as you try to compose generic operations together.
[1]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2030.pdf
[2]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1451.pdf
Basically, every paper that gets submitted by an author will get some amount of discussion time at the next available meeting as well as feedback from the committee on the proposal. I'm not certain what feedback these papers received (we could look through the meeting minutes for the meetings the papers were discussed at to find out, though).
For instance, we added the '_Bool' data type and require you to include <stdbool.h> to spell it 'bool' instead and to get 'true' and 'false' identifiers. This was done to not impact existing code bases that had their own bool/true/false implementation with those spellings. Now that "enough" time has passed for legacy code bases to update, we're looking into making these "first-class" features of the language and not requiring <stdbool.h> to be included to use them. We're doing the same for things like _Static_assert vs static_assert, etc for the same reason.
For example: removing the register keyword, always requiring a return statement, etc etc.
A lot of changes can me made that will make static analysis easier.
There will always be people with 50 year old code bases that will never change (and some c89 compiler will always be there for them), but the language is pervasive enough that it deserves progressive changes to make it (even) simpler and safer and slightly more high level.
Just #include <stdc.h> and be done with it. No need to remember stdio, stdint, stdbool, limits, assert, signal.h, etc, etc.
This new header comes with a guarantee that use of identifiers in the standard-reserved namespace will break your code. Perhaps compilers could even enforce this preemptively.
Note that by including the content of all the headers, you're increasing the chance for collisions with application identifiers. You might consider that more of a benefit than a drawback.
From the outside, after Annex K adoption failure, WG14 doesn't seem to be willing to make C safer in any way.
Are there any plans to take efforts like Checked C in consideration regarding the future of ISO C?
Another thing very cumbersome is to do in C is object creation; creating instantiable objects is possible very cumbersome. Is there some feature in the thoughy process to deal with it. To make it clear, in C we can create a data structure like a Stack or a queue easily. But if the program needs 10 stacks then presently no simple way of achieving it.
To minimize the external identifiers, one could make just the name of a container structure the sole entry access handle, with structure members pointing to the functions. Then use it like:
#include <Mm.h>
if ((new = Mm.allo(size)) == NULL)
Er.abort("out of memory"); Like this like thisAdditionally the used UNICODE_MAJOR and _MINOR are needed. They are always years behind, and you never know which tables versions are implemented.
-Wl,--gc-sectionsEDIT: I work on embedded systems, where C is king, and it seems like a spend an inordinate amount of time working with code generators that build simple tables. All of which could go away with this feature.
I’ve always thought that idiomatic C for constexpr would be to write the code you want to be executed at compile-time in a separate file(s), build it, execute and then #include the result in your program before building the final executable, adding a build step but keeping overall complexity minimal.
This is different from C++ approach, where everything and the kitchen sink is added to the standard and then you have to issue errata for errata for the standard and hope that the compiler you have to use for your current platform is keeping up for the last changes.
Mbed TLS, since I have it in mind from another thread, is also a pretty clean C library for the problem it tries to solve; it's a testament to its design that we (TrustInSoft, who had not participated to its development) were able to verify that some uses of the library were free of Undefined Behavior: https://tls.mbed.org
Opened a random part of musl out of sheer boredom. Here's what I see:
https://git.musl-libc.org/cgit/musl/tree/include/aio.h
A bunch of return codes #defined like so (see https://git.musl-libc.org/cgit/musl/tree/src/aio/aio.c):
#define AIO_CANCELED 0 #define AIO_NOTCANCELED 1 #define AIO_ALLDONE 2
#define LIO_READ 0 #define LIO_WRITE 1 #define LIO_NOP 2
#define LIO_WAIT 0 #define LIO_NOWAIT 1
Why weren't they using an enum instead? I wouldn't sign off on this code (and I don't think it lives up to best practices).
What's the plan for C over the next 5 - 10 years?
What about statement expressions? They're quite useful, and supported by multiple independent compilers.
One goal is to re-unify C with the concurrency object model used by C++ to make std::atomic<T> and _Atomic(T) be ABI compatible as intended in C11. Some small fixes in this area are the removal of ATOMIC_VAR_INIT, clarifying whether library functions can use thread_local storage for internal state, and things along those lines. However, we expect there to be more efforts in this area as we progress the standard.
Do you think Annex K of C11 will be widely adopted by programmers or unused? Why aren't people adopting it?
Do you see the use of any analysis tools that are particularly effective for finding memory safety issues?
C++ added in smart pointers to its specification. Are there any plans to do something similar in future C specifications?
Thanks!
So far, it's not been widely adopted. Part of the issue is that there are specification issues relating to threads and the constraint handlers, and part of the issue is that popular libc implementations have actively resisted implementing the annex.
That said, I field questions about Annex K on a regular basis and there are a few implementations in the wild, so there is user interest in the functionality.
> Do you see the use of any analysis tools that are particularly effective for finding memory safety issues?
<biased opinion>I think CodeSonar does a great job at finding memory safety issues, but I work for the company that makes this tool.</biased opinion>
I've also had good luck with the memory and address sanitizers (https://github.com/google/sanitizers) and tools like valgrind.
> C++ added in smart pointers to its specification. Are there any plans to do something similar in future C specifications?
We currently don't have any proposals for adding smart pointers to C. Given that C does not have constructors or destructors, we would have to devise some new mechanism to implement or replace RAII in C, which would be one major hurdle to overcome for smart pointers.
This can be done in C, but the calling code has to spell malloc and free differently.
In debug mode, configuring malloc to poison (and add fences) on allocation and free finds most of the remaining things.
These techniques tend to have much lower runtime overhead than valgrind (2-digit percentages vs 5-10x), so they can be left on throughout testing and partially enabled in production.
They find >90% of the memory bugs that I write (assuming valgrind finds 100%). YMMV.
why would you have to devise a new mechanism and not borrow one from one of the thousand other mechanisms already existing in PL litterature for this ?
By the time the ISO/IEC TR 24731-1:2007 was released, and then later Annex K added to the C Standard, Microsoft had to decide if they wanted to change the interfaces to conform to the changed standard and re-implement their code bases. They presumably decided that they did not, which I think is a defensible decision.
As to unergonomic, examples please?
As to unergonomic, that's somewhat subjective. But I'm a long-time C practitioner and that's my feel of the API. Constraint handlers are a mistake. Ambient state that is not part of the function interface, as well as asynchronous interaction, make for poor APIs. Constraint handlers are a mismatch for library use of safe functions, as well as kernel environments.
Most functions seem pointless; e.g., snprintf_s. Re-adding gets() in the form of gets_s() seems unhelpful. Why bsearch_s, qsort_s, memcpy_s/memmove_s?? Do you really think strerror_s() is useful? Or strnlen_s()?
Microsoft just changed one bit of the proposal, but no one followed them there. Currently it's the most widely used and worst implemented. I tested all of them.
It solves the bounds checking problem better than _FORTIFY_SOURCE, ASAN and valgrind, because it does the checks always, if compile-time or run-time, independent on the optimizer, the used intrinsics, where valgrind fails, and is much faster than ASAN. Also faster than glibc btw.
IIRC, this macro was added to C11 along with a batch of other "these are optional" macros for atomics, complex, threads, etc. However, I don't recall whether C99 adopted the features as optional features and missed the feature testing macro, or if they were required features in C99 that we made optional in C11.
double (*a)[N][P] = (double (*)[N][P])a_flat;
for (i=0; i<M; i++)
for (j=0; j<N; j++)
for (k=0; k<P; k++)
a[i][j][k] = f(i, j, k);
The alternative would be a_flat[(i*M+j)*P+k] = f(i, j, k);
which is a lot more error-prone. I understand that some implementation (MSVC) declined to implement VLAs, but I really wish that at least VLA-pointers could have remained a mandatory part of C11 and later standards.[
] Has there been any discussion of adding GCC's "typeof" to the standard?Is a controverial feature, that can produce bugs, and are banned in a lot of project (one famouse, the Linux kernel).
In my view C and C++ now almost different languages with a different philosophy of programming, different future, and different language design.
It will be sad if "modern" C++ almost replace C. Many C++ developers use "Orthodoxy C++" https://gist.github.com/bkaradzic/2e39896bc7d8c34e042b, and this shows that people will be more comfortable with C plus some really useful features(namespaces, generics, etc), but not modern C++. I very often hear from my job colleagues and from many other people who work with C++ is how terrible modern C++ (https://aras-p.info/blog/2018/12/28/Modern-C-Lamentations/, https://www.youtube.com/watch?v=9-_TLTdLGtc) and haw will be good to see and use new C but with some extra features. Maybe time to start thinking about evolution C, for example:
- Generics. Something like generics in Zig, Odin, Rust. etc.
- AST Macros. For example Rust or Lisp macroses, etc.
- Lambda
- Defer statement
- Namespaces
What do you think?https://ziglang.org/documentation/master/#Generic-Data-Struc...
https://odin-lang.org/docs/overview/#parametric-polymorphism
By passing -Wl,--wrap=some_function at link time with test code we can then define
__wrap_some_function
that will be called instead of some function. Within __wrap_some_function one can also call __real_some_function which will resolve to the original version if you still want to call the original one. This is especially useful if trying to observe certain function calls in tests that interact with hardware.Do you have any other recommendations/preferences to help with unit-testing C code?
- Basic type inference to reduce keystrokes, and prevent ripples when changing types. (like auto in C++)
- Equality operators defined for structs. Perhaps even lexicographical comparison, if I'm dreaming.
Any thoughts on either of those?
- stricter type-checks on typedef types (useful when passing function parameters) - gcc's ' warn_unused_result' attribute for functions (ensure error returns are checked) - on-entry/on-exit qualifiers for functions (to do things like make sure you lock/unlock semaphores for instance before entry/exit of function) - D language's 'scope' feature (better handling of error path) - loops in the c pre-processor! (better code-gen)
Any chance any of this is on the radar for the next-gen C standard? Some of these are just ergonomics, but the first two might've have saved me some grief a few times.
I wouldn't mind seeing a new feature that does define a new type (one that's identical to, but incompatible with, an existing type), but we can't call it "typedef".
In a sense that feature already exists. You can define a structure with a single member of an existing type. But you have to refer to the member by name to do anything with it.
“Static analysis” may be the wrong name to classify the tools that work in that area, because “static analysis” is usually used for purely automatic tools, whereas the tools used to guarantee the absence of undefined behaviors are not entirely automatic except for the simplest of programs.
Results of a static analyzer are often characterized in terms of “false positives” and “false negatives”. It is a possible design choice to make an analyzer with no false negatives. It is absolutely not impossible! (Some people think it is fundamentally impossible because it sounds like a computer science theorem, but it isn't one. The theorem would apply if one intended to make an analyzer with no false positives and no false negatives—and if computers were Turing machines.)
Analyzers designed to have no false positives are called “sound”. In practice, this kind of analyzer may prove that a simple program is free of Undefined Behavior if the program is a simple example of 100 lines, but for a more realistic software component of at least a few thousand lines, the result will be obtained after a collaborative human-analyzer process (in which the analyzer catches reasoning errors made the human, so the result is still better than what you can get with code reviews alone).
Here is what the result of this collaborative human-analyzer process may look like for a library as cleanly designed and self-contained as Mbed TLS (formerly PolarSSL): https://trust-in-soft.com/polarSSL_demo.pdf?
Does the committee have any plans to make NULL pointer arguments to memcpy non-UB when the size argument is 0?
In the C99 timeframe, we had a rationale document that was separately maintained. My understanding (this predates my joining the committee) is that this was prohibitively labor-intensive and so we stopped doing it for C11. I don't know of any plans to start doing this again, even in a limited sense for justifying UB. That said, we do spend time considering whether an aspect of a proposal requires UB or not, so the rationale exists in the proposals and committee minutes.
> Does the committee have any plans to make NULL pointer arguments to memcpy non-UB when the size argument is 0?
I have not seen such a proposal, and suspect that implementations may be concerned about losing their optimization opportunities from such a change. (Personally, I'd be okay losing those optimization opportunities as this does not seem like a situation where UB is necessary.)
int f (a, n) int n; int a[n][n]; { return a[n-1][n-1]; }
How could one define this function without using the obsolete syntax?
(https://godbolt.org/z/DV9c-C)
Btw, that definition was obsolescent in C89 too.
Plus, of course, there may be existing code using such functions, with parameters in the order that would become impossible if this syntax were disallowed.
Obviously the people who want a Friendly C Compiler do not want to disable all optimizations. This would be easy to do, but these users do not want the stupid 1+2+16 expressions in their C programs, generated through macro-expansion, to be compiled to two additions with each intermediate result making a round-trip through memory.
So the question is: can we get a Friendly C Compiler by enabling only the Friendly optimizations in an unfriendly compiler?
And for the answer to that, I had to write an entire other blog post as preparation, to show that there are some assumptions an optimizing compiler can do:
- that may be used in one or several optimizations, but the compiler authors did not really keep track of where they were used,
- that cannot be disabled and that the compiler maintainers will not consider having an option to disable,
- and that are definitely unfriendly.
Here is the URL of the blog post that I had to write in preparation for the upcoming blog post about getting ourselves a Friendly C Compiler: https://trust-in-soft.com/blog/2020/04/06/gcc-always-assumes... . I recommend you take a look, I think it is interesting in itself.
You will have guessed that I'm not optimistic about the approach. We can try to maintain a list of friendly optimizations for ourselves, though, even if the compiler developers are not helping. This might still be less work that maintaining a C compiler.
So, it's definitely interesting -- I think a lot of odd stuff you can do should probably be undefined. Eliminating pointer accesses after a null check sounds A-ok to me, because your program should never dereference null.
Another interesting thought is requiring more of these things that lead to miscompilation to produce compile time diagnostics.
Btw, there was a thread about it at the time: https://news.ycombinator.com/item?id=8233484.
However, as a user, you can help apply pressure on the vendor to support newer standards. For instance, with Microsoft, you could support this feedback request: https://developercommunity.visualstudio.com/idea/387315/add-...
Really, anyone writing C nowadays should ignore Microsoft's compiler, and tell Visual Studio users to install Clang.
Numeric overflows in things like calculation of buffer sizes can lead to vulnerabilities.
Signed overflow is UB, and due to integer promotion signs creep in unexpected places.
It's not trivial to check if overflow happened due to UB rules. A naive check can make things even worse by "proving" the opposite to the optimizer.
And all of that is to read one bit that CPUs have readily available.
Several places in support functions, I have coded unusually to avoid wrap-around etc. I bet you could devise something like that for (unsigned) multiplication.
The uint16_t got promoted to an int for the multiplication, causing undefined behavior. (if I remember right, the result was assigned to a uint16_t as well, making the intent clear) The compiler then assumed that the 32-bit intermediate couldn't possibly have the sign bit set, so it wouldn't matter if promotion to a 64-bit value had sign extension or zero extension. Depending on the optimization level, the compiler would do one or the other.
This is truly awful behavior. It should not be permitted.
On the other hand, even the function "unsigned mul_mod_65536(unsigned short x, unsigned short y) { return (x * y) & 0xFFFF; }" which the authors of the Standard would have expected commonplace implementations to process in consistent fashion for all possible values of "x" and "y" [the Rationale describes their expectations] will sometimes cause gcc to jump the rails if the arithmetical value of the product exceeds INT_MAX, despite the fact that the sign bit of the computation is ignored. If, for example, the product would exceed INT_MAX on the second iteration of a loop that should run a variable number of iterations, gcc will replace the loop for code that just handles the first iteration.
Maybe also cover some means, algorithms, and code for reporting on the state, status, etc. of the memory use by malloc() and free().
By the way, I know and have known well for longer than most C programmers have lived JUST what the heap data structure, as used in "heap sort", is. But what is the meaning of "the heap" in C programming language documentation?
(2) Cover in overwhelmingly fine detail the "stack" and the chuckhole in the road, stack overflow.
(3) Where to get a reliable package for a reasonable package of code for handling character strings -- what I saw and worked with in C is not reasonable.
(4) From the C programming I did, it looks like a large C program for significant work involves some hundreds, maybe tens of thousands, of includes, inserts, whatever, and what a linkage editor would call external references. There must somewhere be some tools to help a programmer make sense of all those includes and references, the resulting memory maps, issues of locality of reference, word boundary alignment, etc.
(5)How can C exploit a processor with 64 bit addressing and main memory in the tens of gigabytes and maybe terabytes?
(6) How can C support, i.e., exploit, integers and IEEE floating point in 64 and/or 128 bit lengths?
(7) How to handle exceptional conditions with, say, non-local gotos and without danger of memory leaks?
(8) Sorry, but far and away my favorite programming language long has been and remains PL/I, especially for its scope of names rules, handling of aggregates with external scope, its data structures, and its exceptional conditional handling with non-local gotos and freeing automatic storage and, thus, avoiding memory leaks. Of course I can't use PL/I now, but the problems PL/I solved are still with us, also when writing C code. So, how to solve these problems with C code?
(9) For C++, please explain how that works under the covers. E.g., some years ago it appeared the C++ was defined as only a source code pre-processor to C. Is this still the case? If so, then explaining C++ under the covers should be feasible and valuable.
The C language standard does not contain the word "heap" anywhere; as far as C is considered, there is no "heap" in particular.
Strictly speaking, these are implementation details that the C standard leaves unspecified. If you want to know how the memory allocation functions work or methods for inspecting the state of the heap you'll need to look at a specific implementation (e.g., glibc, musl, jemalloc, etc.) since the details can vary wildly between implementations.
> Cover in overwhelmingly fine detail the "stack" and the chuckhole in the road, stack overflow.
Both these are not really specific to C, and there should be a lot of resources you can find that explain these concepts ([0], [1] for some example general explanations). Did you have more specific questions in mind?
> How can C exploit a processor with 64 bit addressing and main memory in the tens of gigabytes and maybe terabytes? > How can C support, i.e., exploit, integers and IEEE floating point in 64 and/or 128 bit lengths?
I think pointer/integer sizes are implementation details. C specifies pointer behavior and minimum integer sizes (and optional fixed-width types), but the precise widths are chosen by the implementation. In the case of floating-point, the sizes are specified by IEEE 754 widths.
In other words, you don't really need to do anything special as long as you pick the appropriate types as defined by your implementation.
> For C++, please explain how that works under the covers. E.g., some years ago it appeared the C++ was defined as only a source code pre-processor to C. Is this still the case?
As far as I know no (production-quality?) C++ compiler has been implemented as a source-level preprocessor for basically the entirety of C++'s existence [2]. The very first "compiler" for C++ was Cpre, back when C++ was still the C dialect "C with classes" (around October 1979), and that was indeed a preprocessor. That was replaced by the Cfront front end around 1982-1983, about when "C with classes" started gaining new features and got a new name. Cfront is a proper compiler front end that output C code, and I think from that point on C++ compilers used "standard" compiler tech.
[0]: https://stackoverflow.com/questions/79923/what-and-where-are... [1]: https://en.wikipedia.org/wiki/Stack_overflow [2]: http://www.stroustrup.com/hopl2.pdf
> Did you have more specific questions in mind?
On stack overflow, my understanding was that could encounter that fatal condition from suddenly a too deep call stack, that is, too many calls without a return. So, if the "stack" is a, say, finite resource, then the programmer should know in the code how much of that resource is being used and act accordingly.
For a preprocessor for C++, I IIRC at one point the definition of C++ was in terms of a preprocessor -- I was just thinking of the definition, that is, get a more explicit definition of C++. I've always understood that always or nearly so C++ implementation was usual compilation. The issue is that at least at one time it seemed difficult to be precise about C++ semantics, that is, what the code would do and how it would do it. Maybe now C++ is beautifully documented.
And this is true, but IIRC statically determining stack bounds for arbitrary programs is not an easy problem to solve, especially if you call into opaque third-party libraries.
> For a preprocessor for C++, I IIRC at one point the definition of C++ was in terms of a preprocessor
I wouldn't know about defining C++ in terms of transformations to C, and searching for that is more difficult. I would guess that the abandonment of the preprocessor approach to compilation would also have meant the abandonment of defining C++ in terms of C, especially once C++ really started picking up features.
> The issue is that at least at one time it seemed difficult to be precise about C++ semantics, that is, what the code would do and how it would do it. Maybe now C++ is beautifully documented.
C++ has had a formal specification since 1998, which might count as documentation for you.
I've typically found that the tradeoffs between security, performance, and implementation efforts are usually more to blame for why writing secure C code is a challenge. There are a ton of tools out there to help with writing secure code (compiler diagnostics, secure coding standards, static analyzers, fuzzers, sanitizers, etc), but you need to use all the tools at your disposal (instead of only a single source of security) which adds implementation cost and sometimes runtime overhead that needs to be balanced against shipping a product.
This isn't to suggest that the language itself doesn't have sharp edges that would be nice to smooth over, though!
https://taas.trust-in-soft.com/tsnippet/
One advantage is that it identifies a LOT of undefined behaviors during execution for which traditional compilation and execution only give puzzling results.
One drawback is that some of the undefined behaviors it identifies are obscure, and for others the message may be unusual. For instance, using a standard function without including the appropriate header may result in a warning about the mismatch between the type in the header and the type of the arguments the standard function was applied to after arguments promotions.
Overall, you may still find it useful for teaching.
Happily, the tooling is the easiest part. Every student has a rasberry-pi running debian, no mouse, no window server, and no extraneous software. You can spool kids up on a nano-based C toolchain in one class period with remarkably few sharp edges. There's even some fun accidental learning the first time they nano their executable file.
I would suggest the following additions;
* The Arduino "language" is C++. Use this as a gentle introduction to C++ as a "better C". From there you can move on to proper C++ (do NOT teach "Modern C++" in the beginning). The intent is to show how "C + some syntactic sugar for expressing abstractions" is quite powerful and that is what is C++. This should prepare the students to embark on a proper study of C++.
* Instead of using the Arduino "language+library" through the IDE, show them how to use the same GNU gcc toolchain to program the MCU directly in C. See Make: AVR programming by Elliot Williams for details. This teaches the students the idea of a "cross compiler toolchain" and all other related matters from first principles.
For a more modern look, i suggest Computer Systems: A Programmer's Perspective by Bryant and O'Halloran
Of course, you would need to pick and adapt the content for your students.
Yes, there are real-world implementations where plain char is unsigned.
I/O functions that take a plain char* are designed to interoperate with char arrays and strings, so passing in unsigned or signed char is a sign that they aren't being used as intended. (Functions that traffic in binary data like fread/fwrite should take void*).
6.2.5p17 The three types char, signed char, and unsigned char are collectively called the character types. The implementation shall define char to have the same range, representation, and behavior as either signed char or unsigned char. 48)
and
5.2.4.2.1 says that width of char, signed char and unsigned char are the same (8).
I am a beginner level programmer and C is not one of the languages for which I have even bothers to write a "hello world" for. That is my level.
As the people that "runs" C, why do we need C? Forget the legacy systems. With fancy languages like Go, Rust, Elixir, Python and the millions others. Of course, the "offsprings" like C++ & C#.
What was the use case that C was designed for (I have read from sources like Wikipedia, would love to hear straight from source)? In 2020, how relevant is C? If someone is going to write a system/application today, why consider C? Do you think, C will be relevant in 5 yrs (I know 1 yr in computing is like 10 yrs for humans)? With all your combined experience in computing over the years and as the members of a team that is guiding a valuable thing like "C". What is your advice/wisdom/thought for us?
Will this be addressed in future revisions of the C standard?
There are a lot of problems that seem a good match for Rust, and Rust is first in my list of programming languages I will never find the time to learn but wish I could.
https://www.f-secure.com/en/consulting/foundry/usb-armory
As does Google,
https://github.com/google/gvisor
https://github.com/google/gapid
Naturally if one is talking about specific uses cases like IoT with a couple of KBs, MISRA-C, or UNIX kernels, then yes Go is not a competitor.
I would suggest that the Standard define directives to demand three modes, with the proviso that a compiler may reject code which demands a mode it cannot accommodate:
1. clang/gcc mode, which would be adjusted to match the way clang and gcc actually behave, as well as anything they want to do but their interpretation of the Standard woudln't allow.
2. precise mode, which behaves as though all loads and stores of objects whose address are taken behave according to a precise memory-based abstraction
3. sequence-based mode, which would allow compilers to hoist, defer, consolidate, and eliminate loads and stores in cases where they honor data dependencies that are visible in the code sequence, but would require that compilers recognize visible dependencies which clang and gcc presently ignore, and would also require that the definition of "based on" used by "restrict" recognize that any pointer formed by adding or subtracting an integer from another pointer by recognized as "at least potentially based on" the former, even in corner cases where clang and gcc would ignore that.
Recognizing mode #1 would avoid allow clang and gcc to keep using their aliasing logic with programs that can tolerate it. Mode #2 would ensure that all programs that have trouble with that logic could have defined behavior by adding a directive demanding it. Mode #3 would allow most of the same useful optimizations as mode #1, but work with a wide range of programs that would presently require `-fno-strict-aliasing`.
If one recognizes the need for different modes, the effort required to describe all three modes would be tractable, compared to the obviously-intractable problem of reaching consensus about how one mode that would need to serve all purposes.
- Are you planning any addition regarding modeling of how modern CPUs work (e.g. pipelines, branches, speculative execution, cache lines, etc)?
PS: Thank you for doing this!
For me, I think it's 'volatile' because, by its nature, you can't describe what it means in the abstract machine very well. For instance, consider a proposal to add something like a "secure clear" function for clearing out sensitive data. The natural inclination is to pretend that data is volatile so the optimizer won't dead-code strip your secure clear function call, but that leaves questions about things like cache lines, distributed memory, etc.
> - Are you planning any addition regarding modeling of how modern CPUs work (e.g. pipelines, branches, speculative execution, cache lines, etc)?
Maybe? ;-) We tend to talk about features at a higher level of abstraction than the hardware because hardware changes at such a rapid pace compared to the standards process. So we largely leave hardware-specific considerations as a matter of QoI for implementers.
However, that doesn't mean we wouldn't consider proposals for more concrete things like a defensive attribute to help mitigate speculative execution attacks.
Basically, we prefer seeing features that real users have used as opposed to an experimental branch of a compiler that doesn't have usage experience. Knowing it can be implemented is one thing, but knowing users want to use it is more compelling.
First off thank you so much for taking the time to answer questions.
As a new programmer starting with C I am trying to learn how to go from a beginner to an intermediate any recommendations of projects to help learn C?
It is difficult for me to find projects that I see are "valuable" for a lack of a better term.
Thank you!
For instance, a lot of redundant code (or ugly macro business) could be neatly replaced by function templates. Even just template functions with only POD values allowed would be a great readability improvement.
Why not mandate a warning every time the compiler detects and makes use of UB? It would solve SO many issues. If you are looking to improve security of C programs, then letting the user know what the compiler does should be number one.
Try to convert as many UB's to Platform specific, as possible would also be a big help.
I would love to see native vector types. Its time. Vector types are now more common in hardware then float was when it was included in the C spec. Time to make it a native type. Hoping the compiler does the vectorization for you is not good enough.
Allow for more then one break.
for(i = 0; i < n; i++) for(j = 0; j < n; j++) if(array[i][j] == x) break break;
is equal to:
for(i = 0; i < n; i++) for(j = 0; j < n; j++) if(array[i][j] == x) goto found; found :
Because that's hardly ever what happens, except when it actually does, and compilers do an increasingly good job of issuing diagnostics in that case. If you actually mandated it, no compiler today would come close to being standards compliant. This comes close to making the language unimplementable.
The most common issue with UB and optimizations is not that "compiler detects UB and does something with it," it's that compiler analyzes and optimizes code with the assumption that UB doesn't actually happen. It doesn't know whether it does (and in general, it is impossible to tell whether it would happen -- it's something that might or might not happen at run time, and proving it one way or another amounts to solving the halting problem), it just assumes it doesn't.
And if one mandated compilers to report every time they make an optimization that is valid under the assumption that the program is well behaved, then you would never finish reading compiler output. Or you would turn off optimizations.
find_in_array_loop:
for(i = 0; i < n; i++)
for(j = 0; j < n; j++)
if(array[i][j] == x)
break find_in_array_loop;Have you considered adding access to structure members by index or by string name? Have you considered dynamic structures?
I'm not certain about the historical answer to this, but I do know that we're currently considering a proposal to introduce an exact bit-width integer type '_ExtInt(N)' to the language, and how to handle format specifiers for it is part of those discussions, so we are considering some changes in this area.
> Have you considered adding access to structure members by index or by string name? Have you considered dynamic structures?
I don't recall seeing any such proposals. I'm not familiar with the term "dynamic structures", what do you have in mind there?
Please, please, please pick short and descriptive format specifiers, like %[suf]\d+, ie
s64 v=somenumber;
printf("%s64\n", v);
_ExtInt(N) and PRIx64 etc look absolutely horrid. u?int\d+_t are also really bad, it would be great to have just [suf]\d+ as types, where \d+ is 8, 16, 32, 64 for [us] and 32 and 64 for f.>what do you have in mind there?
Say like VLAs but structures with members that are dynamically defined and used.
That's my personal preference as well. Using the PRI macros always makes me feel sad.
> Say like VLAs but structures with members that are dynamically defined and used.
Ah, no, I don't recall any proposals along those lines. It's an interesting idea, and I'd be curious what the runtime performance characteristics would be vs what kind of new coding patterns would emerge that you couldn't do previously though!
printf("U32: %" PRIu23 ", U64: " PRId64, (uint32_t)1, (int64_t)2);
Perhaps not as handy as %u32 or %s64, but it's here. uint64_t foo = ...;
printf("foo = %ju\n", (uintmax_t)foo);
/* OR */
printf("foo = %llu\n", (unsigned long long)foo);Have you ever considered or will you consider deprecating char, int, long, (s)size_t, float, double and etc in favour of specific length types?
Will you ever add / have you considered adding [su]\d+ and f\d+ as synonyms for those mentioned stdint.h?
Since char is signed on most platforms, arm eabi being an exception and even there it's really just a matter of compile time flags, will you ever just drop char from being able to be either and just say it's signed, as int is also signed?
Will you ever define / have you considered defining signed overflow behaviour?
C does provide fixed width types like uint8_t, uint16_t, uint32_t, and uint64_t. These are optional types because they can't be implemented on implementations that don't have the appropriate word sizes. We also have required types such as
uint_least16_t uint_least32_t uint_least64_t uint_least8_t
I would go beyond that, requiring all sizes that are a multiple of 8 bits from 8-bit through 512-bit. This better supports cryptographic keys and vector registers.
Why?
If not deprecate, then at least make fixed width types as equivalent members to them, ie all char based apis should accept s8 (typedef signed char s8) and all int based apis should accept s32.
https://ericlippert.com/2020/02/27/hundred-year-mistakes/
int x = 0, y = 1, z = 0;
int r = (x & y) == z; // 1
int s = x & (y == z); // 0
int t = x & y == z; // 0 UGH
"m" is the same as "w", but does not truncate the file. In POSIX terms, it doesn't add O_TRUNC to the flags.
There is "r+", of course; but "r+" requires that the file exists already. In POSIX terms, "r+" does not include the O_CREAT flag.
fopen("foo", "m") creates the file if it does not exist, and opens it for writing. The stream is positioned at the beginning of the file without truncating it.
We can sort of emulate it with fopen("foo", "a"), then fclose, then open with "r+".
For the first one, I can attempt a guess: maybe it was feared that making the result of localtime thread-locale would break some programs? You could build such a program on purpose, although I am not clear how frequently one would write one by accident.
Anyway, localtime_r is the function that one should use if one is concerned by thread-safety. A more likely answer is that no Unix implementation bothered to fix localtime because the proper fix was for programs to call localtime_r.
How I can find help for this?
1) namespaces, so function names don't need to be 30 characters to avoid naming collision
2) guaranteed copy elision or RVO -- provides greater confidence for common idioms and expressivity compared to passing out parameters
Is it fair to assume that hardware-related decisions occur in an environment where members who are sponsored by vendors argue their employers case, rather an a neutral one?
---
[1] E.g., because some hardware's behavior may more naturally implement the operation.
The C committee has a number of implementation vendors on it (GCC, Clang, IBM, Intel, sdcc, etc) and these folks do a good job of speaking up about the hardware they have to support (and in some cases, they're also the hardware vendor). If needed, we will also research hardware from vendors who have no active representation on the committee, but this is usually for more broad changes like "can we require 2's complement?".
> Is it fair to assume that hardware-related decisions occur in an environment where members who are sponsored by vendors argue their employers case, rather an a neutral one?
In my experience, the committee members typically do a good job of differentiating between "this is my opinion" and "this is my employer's opinion" during discussions where that matters. However, at the end of the day, each committee member is there representing some constituency (whether it's themselves or their company) and votes their own conscience.
For example, I have a arbitrary number of includes, each of them declare a struct that need to be listed later on.
#define MOD_LIST // start with an empty list
#include "mod/a.c"
// MOD_LIST is: a,
#include "mod/b.c"
// MOD_LIST is: a,b,
Module modules[] = {
MOD_LIST
}ender1235, if you don't see an email address there, email hn@ycombinator.com and I'll put you in touch.
When asked, "Where do you think C is going?", one of them said, "I don't see it going anywhere." I took that as a good thing, meaning, they're concerned about backward compatibility, compiler performance, and only adding features when there's a wide concensus in implementation - which is a high enough hurdle that avoids the feature bloat of C++.
Overall, I felt the "conservatism" refreshing, to keep the language small.
On the other hand, there are several common feature requests I see in this thread that probably will never be part of the language, since it moves slow relative to other languages.
_If, _Ifdef, _Ifndef
inside function macrosfor example:
#ifdef SOME_CONST
#define WHATEVER(w, h, a, t, e, v, e, r) \
... common part ... \
... for SOME_CONST ... \
... common part continued ...
#else
#define WHATEVER(w, h, a, t, e, v, e, r) \
... common part ... \
... when SOME_CONST not defined ... \
... common part continued ...
#endif
With _Ifdef, the above could be written like: #define WHATEVER(w, h, a, t, e, v, e, r) \
... common part ... \
_Ifdef(SOME_CONST, \
(... for SOME_CONST ...) , \
(... when SOME_CONST is not defined ...)
) \
... common part continued ...
With these, one could also do: #define FACTORIAL(n) _If(n == 0, 1, (n) * FACTORIAL(n))
int f = FACTORIAL(6);
turns into:
int f = (6) * (5) * (4) * (3) * (2) * (1) * 1;That would be very useful, I think. It might help with code duplication in function macros.
Maybe _Switch/_Case thereafter.
#ifdef SOME_CONST
#define HAS_SOME_CONST \
... for SOME_CONST ...
#else
#define HAS_SOME_CONST \
... when SOME_CONST not defined ...
#endif
#define WHATEVER(w, h, a, t, e, v, e, r) \
... common part ... \
... HAS_SOME_CONST ... \
... common part continued ...- Why no sized text strings?
- Why is there no hash data type?
- Where's the linked list?
- Why no package management as part of ecosystem?
What is the modern rationale?
Caveats:
- I'm not implying any need for object-orientation (OOP)
- I'm fully aware I can write these myself and can access third party libraries that have each laboriously implemented their own versions.
- I'm interested in why these are not native C constructs in 2020. I appreciate why not in 1980.
I tend to use glib for my (academic) code for pretending C is a high-level language. It also seems to make up for implementation-dependent functions in C and many portability issues. Also, IMO, vala > C++.
My question is, really, are there any other tools for high-level C programming and do you know of any disadvantages of the Gnome stack?
This might not be too deep a question on the C language in regards to this book, but I've been wondering, why did you decide to have an eldritch horror as the book's cover?
The C==Sea brings to mind the book Expert C Programming: Deep C Secrets.
Sounds like you don't care for Annex K. What don't you like about it?
http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1967.htm
(1) runtime constraint handler callbacks are a terrible API.
(2) The additional boilerplate doesn't buy us anything — the user can still specify the wrong size.
(3) The Annex invents a feature out of whole cloth, rather than standardizing existing practices. There are no performant real-world implementations that anyone uses. Microsoft's similar functionality is non-standard.
For instance, the macOS clang environment does not define this symbol. Is their implementation of wchar_t or <wctype.h> lacking some aspect of Unicode support?
Clang defines that macro for some targets (like the Cloud ABI target), but not others. I'm not certain why the macro is not defined for macOS though (it might be worth a bug report to LLVM, as this could be a simple oversight).
* First call setlocale(LC_CTYPE, "en_US.UTF-8")
* Next feed the UTF-8 string representation of every Unicode codepoint one at a time to mbstowcs() and ensure that the output for each is a wchar_t string of length one
* If all input codepoints numerically match the output wchar_t UTF-32 code units, then the implementation is officially good, and should define __STDC_ISO_10646__?
I could use a union type, but that adds extra memory operations, and is finicky.
Is there a better way?
# from Chp2 of Effective C
1) Are there any plans or discussions on having a subset/extension of C that is designed for formal verification? Much like SPARK with ADA.
2) Is there no plan to support GC? Even as an extension of C?
I couldn't find that again in one minutes, but here is the text version: http://web.archive.org/web/20030222051144/http://home.earthl...
A paperbook is less likely to be lost and K&R is the more affordable reference to C rather than ISO 9899.
if you're interested in looking at how C can be used in embedded realtime operating systems, i recommend diving into:
https://github.com/ARMmbed/littlefs
(i'm not affiliated.)
it's a lean, logging flash filesystem implementation and i recommend it because the research, rationales, documentation, organization, codebase, test harness, and public API ergonomics all impressed me a lot. it was written for the mbed OS, but it is so well designed that i could integrate it into any realtime OS without too much trouble. and the documentation is thorough enough that after skimming the wikipedia article for filesystems, and maybe an article on how flash chips read and write data, you'll be able to work your way through it. i learned a lot by reading through that repository.
Anyway, here's some questions:
- What kind of programs would you say C is a good fit for?
- There is some catching up to do for C. Is there a roadmap for C improvement, or even a recommendation of C++ things that fit somewhat in the style/philosophy of C? For example, I'd recommend not using the C++ smart pointers stuff, while still using C++ threads and lambdas.
Also, you should include programmers from other fields in your committee. Game (engine) developers, HFT programmers are used to lower level styles of coding and align with your perspective.
I am not on the MISRA committee, but I believe they talk a bit about their public roadmap in this video: https://vimeo.com/190304951
The list is very much biased by the sort of analyzer we provide. There are certainly plenty of non-embedded codebases in C and of developers paid to maintain and extend them, it's just that we currently do not work with them as much.
I do not know about whether the compensation is better or worse than for other technologies.
If there exists any memory block allocated using malloc() / calloc() / realloc() which has not been free()'d, at the end of the program, they would be free()'d automatically.
One can easily do it with keeping a linked list and using atexit(), but, can it be added to the standard?
A general question, will anything, any feature, which is "easy" to implement in pure C, like array knowing its own length or pascal strings, NOT be allowed to be in C standard, even if it is widely used, maybe almost everywhere?
If OSes do that, why not standardize that in C?
void callback(int x, void *) // VOID STAR UNUZED, SO ANON
{
foo(x);
}In particular, section 6 is the best resource I know of for explaining the often counterintuitive relationship between arrays and pointers.
2. Why it is harder to find lgpl licenced libraries to access windows directories over network like jcifs pysmb (and libraries overall) when needed to close most part of software source to sell small softwares to businesses?
3. If you needed to combo C with another language to do everything you need to do forever and never look back what other language would that be?
Thanks for this!
This helps bringing these languages to embedded targets with closed toolchains (with an existing C compiler).
Will there be developments to use a subset of C as a “portable assembly” in a standard way? Like there is WebAssembly for JavaScript.
There are pieces of software that should be given priority for a rewrite in Rust, but most of C software is never going to be rewritten, because there is simply too much of it.
Therefore, even if C did not have any advantage of its own over Rust, there would still be legacy software to maintain and to extend.
The advantages of C include that sometimes, an embedded processor with a proprietary instruction set is provided by the chipmaker with its own C compiler, which is the only compiler supporting the instruction set; that C is still currently used to write the runtimes of higher-level languages (I'm familiar with OCaml, but it isn't too much of a stretch to imagine that the runtimes of Python, Haskell,… are also written in C).
It goes deeper than that, in a couple of places Rust depends on the C standard: the fixed-layout `#[repr(C)]` structs (without that attribute, the compiler is free to reorder the struct fields; with that attribute, it's laid out the way C would do it), and the `extern "C"` function call ABI. The way to call any other language from Rust, or Rust from any other language, is to go through `extern "C"` functions passing `#[repr(C)]` structs. So even if the C language dies one day, parts of it will live in Rust forever (or as long as the Rust language lives).
I sincerely hope this is not the general attitude of the standards committee. Some of us actually prefer C, and would like to see the language continue to flourish.
This looks to be a hell'va' good tool chain. I'm playing with as of yesterday.
The licenses of the majority of third-party libraries available for C are GPL, do you think this makes harder reusing code to sell software?
You're not the only person who misses the old newsgroups! The format that Hacker News uses is one that became sort of standard on the web in the early 2000s. It works differently than usenet did, but you get threaded comments in the sense that replies are nested under the posts they're replying to.
Big question, how to start programming in C on a high professional level for somebody self schooled in it? Is there a way to cut the corner, without having to go through 10+ years trial and error to gain experience?
Anything for somebody ready to sit, study, and practice for a few hours a day?
Head First C - Griffiths and Griffiths
Expert C Programming: Deep C Secrets - Peter van der Linden
Modern C - Jens Gustedt
C Programming: A Modern Approach - K. N. King
21st Century C: C Tips from the New School - Ben Klemens
Understanding and Using C Pointers - Richard Reese
C Interfaces and Implementations: Techniques for Creating Reusable Software - David R. Hanson
The Standard C Library - P. J. Plauger
How likely would the standard be to accept a proposal to add compile time reflection to the preprocessor, or even adopt C++'s constexpr?
My use case is creating a global array in a header from static compound literals in multiple source files at compile time, and outside of some crazy clang-tblgen type solution, or very platform specific linker hacks, it's completely unsupported by C.
Cheers from the shadowland :)
- Languages like Rust will gain more mindshare over the next decade, and be used in more and more new projects, but there are billions of lines of existing code in C, and those aren't going away.
- Hardware architects, for better or worse, largely think about software in terms of [a somewhat dated and idealized mental model of] C. So if you want to be able to converse with architects (which anyone doing systems programming should want to do), you need to have some basic fluency with C.
You need to know enough C to interface with the OS, and enough C to talk about memory layout, memory management, dynamic libraries, ABI, etc.
Most higher language runtimes need C, even with a self hosting compiler. Not being able to work on the C parts is limiting.
You also need to know enough assembly to be able to understand what the compiler did with your own code, even if you never write assembly yourself. Not being able to compare the disassembly to the high level language to understand why it doesn't work (or is order of magnitude slower than expected) is limiting.
s8 buf[enoughspace];
snprintf(buf, sizeof(buf), "%f,%f,%f", your, three, values);
sscanf(buf, "%f,%f,%f", &your, &three, &values);
Do the job?You need to first store the current locale, change the locale to one that doesn't use a comma as the decimal point, perform the above, and set the locale back. Plus, there's no threadsafe way to do this, since the locale is process-wide.
* Why can't the learning curve be solved using tools? * Why don't we actively promote more higher level languages which are implemented in C (by fewer people)?
I mean by that logic, Assembly could be deem even simpler, yet writing OR reading programs in Assembly is absolutely not simple at all.
At the end of day, one has to write programs that solve (complicated) problems, and learning how to do that in C is difficult, thus the learning curve deemed higher when it comes to writing professional C.
I can guarantee you that writing professional Go or Java and writing correct programs in both takes way less effort than with C, for use cases that would make Go or Java viable.
So I don't think C has a very high learning curve, C++ on the other hand...
2. When we will get the Secure Annex K extensions?
3. When we will get mandatory warnings when the compiler decides to throw away statements it thinks it doesn't need? Like memset or assignments. Compilers are getting worse and worse, and certainly not better.
ad 1) Strings are Unicode nowadays, not ASCII. Nobody uses wchar but Microsoft. Everybody else is using utf8, but there's nothing in the standard. Not even search functions with proper casing rules and normalization. Searching for strings should be pretty basic enough.
2. The usual glibc answer is just bollocks. You either do compile-time bounds checks or you don't. But when you don't, you have to do it at runtime. So it's either the compilers job, or the stdlib job. But certainly not the users.
[1] Watcom C Library Reference Version 1.8. Open Watcom. 2008. ftp://ftp.openwatcom.org/manuals/current/clib.pdf
[2] Safe C Library — A full implementation of Annex K https://github.com/rurban/safeclib/
[3] slibc https://code.google.com/archive/p/slibc/
But at least add wcsnorm and wcsfc as I implemented them in the safeclib are required. Not even coreutils, grep, awk, ... can search unicode strings.
And u8 library variants of str* and wcs* are definitely needed, maybe just with uchar* not char*.
For reference I still use The C Programming Language by KERNIGHAN/RITCHIE and The Standard C Library by PLAUGER.
In my view what programmers need the most is good practices rather than any syntactic sugar.
I prefer C rather than any other programming language for its conciseness.
There is opportunities for any new programming language to replace C if it is at least backward compatible with K&R C SE (aka ISO C90) and provides a portable access to de facto standard hardware acceleration such as SIMD instructions for vector computing.
For now we have to write in assembly language SIMD optimized libraries in order to get the full calculation power of modern processors.
For programmers who expect C to bring them a hot drink, I would recommend them to stick with the bloated C++ framework which sometimes enlarges your p*s. :-P
It seems cowards don't have any argument. :-)