Lurker News
Hi HN,

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!

Comments (962) 182 threads

Earlier comments
eqvinox6 replies#
What's the best way to deal with "transitive const-ness", i.e. utility functions that operate on pointers and where the return type should technically get const from the argument?

(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...)
DSMan195276#
The straight-forward approach is just two functions, one with `const` and one without (You can make one of them `static inline` around the other and do some casting to avoid implementing the same thing twice).

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.

DougGwyn1 reply#
Many uses of strchr do write via a pointer derived from a non-const declaration. When we introduced const qualifier it was noted that they were actually declaring read-only access, not unchangeability. The alternative was tried experimentally and the consequent "const poisoning" got in the way.
coliveira1 reply#
I believe C is doing the right thing. Const as immutability is a kludge to force the language to operate at the level of data structure/API design, something that it cannot do properly.
moonchild#
Have you ever used a high-level statically-typed language, e.g. haskell?
pascal_cuoq#
Speaking as someone who is not in the committee but has observed trends since 2003 or so, I would say that solving this problem is way beyond the scope of evolutions that will make it in C2a or even the next one.

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.

msebor#
The committee has reviewed a proposal (document N2360) to for const-correct string functions.

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.)

flatfinger#
How about allowing `return` to be used as a qualifier within a function or prototype's argument which, if present, would adjust the qualifiers of the function's return value to match those of the argument, e.g. adding "const" or removing "volatile" as appropriate?

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).
_kst_#
strchr() is one of several C library functions that have this issue.

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.

rmind3 replies#
A lot C programmers prefer to keep structures within the C source file ("module"), as a poor man's encapsulation. For example:

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++). :)

msebor1 reply#
The ELF visibility attributes solve the part of the problem at the binary level (by hiding private library APIs from the application). The rest should be doable by structuring the project sources and headers in a suitable way.
loeg#
ELF is very much not part of the C standard.
pascal_cuoq2 replies#
I am sorry I do not have an answer to your question. It's a very valid one and I would be interested in any pointer to an answer.

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.

beefhash3 replies#
Wait, doesn't this mean that the BSD sockets API is inherently dependent on UB, casing different socket types to each other and sometimes only using the first few members, or am I misunderstanding you?
pascal_cuoq8 replies#
Yes and no.

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...

Continue this thread — 8 replies

emilfihlman#
Yeah, it depends on well agreed convention but which is ub according to the standard.
loeg#
Yeah, the BSD socket API is kind of terrible like that. You could consider it an unspecified union type, or use memcpy() exclusively to access it safely.
rmind#
I assume you mean something like that:

    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.
defectbydesign#
There are already "Name Spaces" in C and modules are actually object files or libraries.

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.

floatms4 replies#
1. How likely are named constants of any types to be included in C2x? I'm referring to the idea of making register const values be usable in constant expressions.

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 three
msebor1 reply#
I'd expect a proposal for (1) to be well received. The only proposal I recall that deals with (2) is http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2067.pdf. I think it's still being discussed. (3) is highly unlikely if it involved ABI changes. Even if it could be done without such changes unless there is a precedent for it in an existing compiler (and preferably more), it would likely be a tough sell.
floatms#
Is the linked proposal really dealing with unnamed struct types? I skimmed it and it seems like it is dealing with named constants. Also, is there a proposal for (1) currently, or is someone planning on writing one? Regarding (3), yes, this one was mostly wishful thinking.
pascal_cuoq1 reply#
3. would have to be a new mechanism for variadic functions, that would have to be distinguished in header files from the old mechanism with which it is incompatible. So this proposal would imply some new keyword or syntax. I am not in the committee, but I don't think this is going to happen. The improvement is way too incremental to force a new syntax.

(The committee is fine with incremental improvements, but new syntax need to have strong motivation behind it, much stronger than this.)

floatms#
Yes, I know that this is the most disruptive out of the three. The implicit parameter more so than the va_ptr() intrinsic (in my opinion), but I understand that changes like these are not very well motivated (except for a slightly nicer developer experience).
flatfinger#
What is really missing from the C "aliasing" rules is a recognition that an access to a pointer/lvalue which is visibly freshly derived from another is, depending upon the form of derivation, either a definite or potential access to the former [in the former case, anything that couldn't be accessed by the original couldn't be accessed by the derived pointer/lvalue; in the latter case, the derived pointer/lvalue might access things the original could not].

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.

r12477#
I have incorporated the following macro abuse to prepend the number of arguments to a variadic functions into my projects: https://gist.github.com/61131/7a22ac46062ee292c2c8bd6d883d28.... It does introduce some overhead, but it suits my needs for the projects that I am working on.

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.

rseacord2 replies#
Many of your remaining questions have devolved into "When will I see my favorite feature xyz appear in the C Standard?" The answer in most cases is "that depends on how long it takes you to submit a proposal". Take a look at http://www.open-std.org/jtc1/sc22/wg14/www/wg14_document_log... for previous proposals and review the minutes to see which proposals have been adopted. In general, the committee is not going to adopt proposals for which there is insufficient existing practice or haven't been fully thought out. There are cases where people have come to a single meeting with a well-considered proposal that was adopted into the C Standard. I wrote about one such case here: https://www.linkedin.com/pulse/alignment-requirements-memory... Alternatively, you can approach someone on the committee and ask us to champion a proposal for you. It is likely that we'll agree or at least provide you with feedback on your proposal.
sramsay1 reply#
Thanks to one and all for this AMA! The massive number of comments testifies to the continuing interest in C, and I think we're all grateful to all of you for your expertise, your patience, and your even-handed responses.
flatfinger#
Is the present purpose of the Standard to:

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?

flatfinger#
I don't know if you saw my question right below, since I guess I replied to the wrong post, but I'd be really interested to know how you view the purpose of the Standard. For years, the language has been caught in a catch-22 where the authors of the Standard have seen no need to have it recognize constructs that compilers have, almost unanimously, processed usefully for years without being required to do so, but some compiler maintainers interpret the failure to mandate such constructs as deprecation.

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?

Load more comments