First Draft: Making printf @safe

Nick Treleaven nick at geany.org
Fri Aug 2 14:22:01 UTC 2024


On Wednesday, 17 July 2024 at 00:42:03 UTC, Walter Bright wrote:
> https://github.com/WalterBright/documents/blob/ed4f1b441e71b5ac5e23a54e7c93e68997981e9a/SafePrintf.md

> This proposal will cause the format specifier to be rewritten 
> to match the argument type, if the format specifier is %s.

Dennis [has pointed 
out](https://forum.dlang.org/post/vnhnhkxxurgnpvpoilzp@forum.dlang.org) that this can corrupt memory (in a @system or @trusted function) just by simple refactoring:

> You would think it's safe to transform this:
```d
int x;
...
printf("x = %s\n", x);
printf("x = %s\n", x);
```
> Into this:
```d
const(char)* fmt = "x = %s\n";
printf(fmt, x);
printf(fmt, x);
```
That's quite a pitfall and easy to overlook in code review. I 
suggest removing that feature for argument types other than 
character arrays.

> If the format specifier is %s and the corresponding argument is 
> a D array of char or wchar_t, the format will be replace with 
> %.*s (or %.*ls) and the argument will be replaced with two 
> arguments

I think that's fine, because D doesn't allow passing arrays to 
variadic arguments. So if those calls were refactored, they would 
cause a compile-time error.


More information about the dip.development mailing list