logoalt Hacker News

Arch-TKtoday at 2:02 PM2 repliesview on HN

It's incredibly common for people talking about C online or even in books (be that blog posts, side notes, tutorials, guides) to constantly make mistakes like these.

C seems to be one of those languages where people think they know it based on prior and adjacent experience. But it is not a language which can be learned based on experience alone. The language is full of cases where things will go badly wrong in a way which is neither obvious nor immediately evident. The negative side effects of what you did often only become evident long after you "learn" it as something you "can" do.

If you want to write C for anything where any security, safety, or reliability requirement needs to be met, you should commit to this strategy: Do not write any code which you are not absolutely certain you could justify the behaviour of by referencing the standard or (in the case of reliance on a specific definition of implementation defined, unspecified, or even (e.g. -ftrapv) undefined behaviour) the implementation documentation.

If you cannot commit to such a (rightfully mentally arduous) policy, you have no business writing C.

The same can actually be applied to C++ and Bash.


Replies

zahlmantoday at 5:06 PM

> Do not write any code which you are not absolutely certain you could justify the behaviour of

Doing this for every line is impossibly tedious (people will quickly tire of it), and detecting where the code is actually non-trivial requires a kind of epistemic humility that doesn't come naturally to most.

Better if we can use languages that don't assume such demands are necessary for the compiler to be able to generate performant code.

ueckertoday at 2:45 PM

It is definitely not a language that can be learned by reading blogs.

But the advice really applies to almost everything you do related to security, safety and reliability. In other languages you may have a panic in production or a supply chain issue.