Make printf safe

Timon Gehr timon.gehr at gmx.ch
Sun Jul 14 14:06:39 UTC 2024


On 7/13/24 22:39, Walter Bright wrote:
> I propose that the compiler rewrite:
> 
> ```
> char[] name;
> printf("name = %s\n", name);
> ```
> into:
> ```
> printf("name = %.*s\n", cast(int)name.length, name.ptr);
> ```
> (and mark any other use of %.*s as unsafe)

This part is actually not memory safe.


In general, I guess provided we can get it right, extending the 
`pragma(printf)` checks in `@safe` code is indeed an improvement to the 
language, though I think not a lot of people need this.

You should probably have to mark the `printf` prototype as `@trusted` 
for this to work though. (There are `pragma(printf)` functions that 
still have a `@system` interface even when there is nothing wrong with 
the format string and arguments, e.g. `sprintf`.)

For everyone who is not aware, here's D's existing `printf` support:
https://dlang.org/spec/pragma.html#printf

Probably `pragma(scanf)` would need to get similar treatment.



More information about the dip.ideas mailing list