Make printf safe

Nick Treleaven nick at geany.org
Thu Jul 18 16:45:02 UTC 2024


On Wednesday, 17 July 2024 at 17:24:15 UTC, IchorDev wrote:
> On Wednesday, 17 July 2024 at 09:20:23 UTC, Nick Treleaven 
> wrote:
>> The idea is to make certain calls of `printf` safe when the 
>> first argument is a string literal:
>> ```
>> char[] s;
>> printf("%s\n", s);
>> ```
>> See https://forum.dlang.org/post/v775k1$1tmj$1@digitalmars.com.
>
> And the function will still perform pointer arithmetic.

So does copying a D array, but that is safe.

Responding to your post in DIP development here (because that's 
for reviews):

> strlen assumes that s is zero-terminated

```d
pragma(msg, printf) printf(const char* fmt, ...) @safe;
```
What the above would mean is that `printf` is @safe only when 
`fmt` is given a string literal. String literals are *guaranteed* 
to be zero-terminated, so there's no assumption of that here. If 
the pragma checks are not met, `printf` is actually treated as 
@system.

> Any function that traverses a C string passed as an argument 
> can only be @system. Any function that trusts a separate 
> parameter for array bounds can only be @system.

That requires modification for this proposal. It is true when 
given a char* for the format parameter. But when a string literal 
implicitly converts to char*, it has a safe interface due to the 
pragma, because the literal is statically allocated and is never 
accessed past its allocation when called from @safe code.


More information about the dip.ideas mailing list