Make printf safe

Walter Bright newshound2 at digitalmars.com
Mon Jul 15 18:36:07 UTC 2024


On 7/14/2024 7:06 AM, Timon Gehr wrote:
> 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.

How is it not 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.

*I* need it :-) It's an enabling feature, in that it enables me to much more 
fully transition dmd away from using 0 terminated strings.


> 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`.)

It would apply to snprintf, but not sprintf which is not fixable.


> 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.

Possibly, but scanf is almost never used :-/



More information about the dip.ideas mailing list