Make printf safe
Walter Bright
newshound2 at digitalmars.com
Sat Jul 13 20:39:32 UTC 2024
The idea is printf is already largely safe:
```
printf("number = %d\n", 3);
```
is perfectly safe.
Unsafe problems:
1. if the arguments and their types do not match the format string. D already
checks for that, so we're good there.
2. if a pointer is passed to %s:
```
char* name;
printf("name = %s\n", name);
```
That's unsafe. We normally fix this with:
```
char[] name;
printf("name = %.*s\n", cast(int)name.length, name.ptr);
```
Which is safe, because we know how printf() works. 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)
We can go further, and realize that since we already check the format string
against the arguments, we can rewrite the format string to match the arguments:
```
printf("number = %s\n", 3);
```
becomes:
```
printf("number = %d\n", 3);
```
which makes it much simpler to use printf. I can never remember which format is
for size_t, for example.
The one format specification (I forgot which one) which assigns a int value
through a pointer, can simply be marked as unsafe.
Of course, this only applies if the format string is a literal, not a variable.
Since dmd already scans and checks the format string against the argument list,
most of the work for this proposal is already done.
More information about the dip.ideas
mailing list