C is Brittle D is Plastic

Derek Fawcus dfawcus+dlang at employees.org
Tue Apr 7 09:23:45 UTC 2026


On Tuesday, 7 April 2026 at 05:20:38 UTC, Walter Bright wrote:
> On 4/5/2026 3:28 AM, Derek Fawcus wrote:
>> It has always been possible to avoid pointer decay for fixed 
>> size buffers, it is just that that the syntax is ugly, and the 
>> use cases are limited.
>
> I've never seen it used. It's too awkward.

For returning buffers, yes.  For passing buffers in to functions, 
it is actually not that bad, and one now generally gets 
complaints from the compilers over errors.  Something like this:

```c
void caller() {
     char buffer[23];

     int n = callee(&buffer);
}
int callee(char (*buffer)[23]) {
     enum { buflen = sizeof *buffer };
     return snprintf(*buffer, buflen, "Foobar!");
}
```
possibly using another enum, or #define rather than than the 
literal 23.

>> Having been assigned to work on some old code, adjusting APIs 
>> to use that form (or where difficult the newer "char 
>> buf[static X]" combined with static analysis (and warning 
>> flags) has been an easy improvement.
>
> Static analysis cannot reliably detect array overflows. It's 
> that old halting problem.

It is not about being reliable, it is about catching the low 
hanging fruit,
and catching them as early as possible.  The compilers now often 
flag that case,
3rd party SA catches a bit more.  Covering the other instances 
can often be
achieved with various dynamic sanitisers (ASAN, bounds sanitizer, 
etc).

I actually found and fixed a handful of errors simply from 
changing the callee
definition in a few instances to that 'buf[static X]' form, and 
having the gcc
flag it.  In that case because there were so many 3rd party SA 
complaints that
folks had stopped paying attention to them. So it is not just 
capabilities,
it is an issue of practices.

>> Rewriting in a different language is a much more risky task, 
>> and generally an impossible sell to management.
>
> AI has proven to be useful in translating code to a different 
> language.

The major issue there is review bandwidth.  It probably ain't 
going to happen,
rewrites from scratch are more likely.

What I am following with interest is Fil-C, which does add a GC.  
If the performance
cost can be sufficiently improved, then that strikes me as the 
reasonable way forward
for legacy C code, until it is chucked out and replaced by 
something written in a
different language.

DF



More information about the Digitalmars-d mailing list