A possible feature request: Make writef with %s call to!string for char* parameters

Steven Schveighoffer schveiguy at yahoo.com
Tue Jul 12 05:12:35 PDT 2011


On Mon, 11 Jul 2011 16:37:12 -0400, Andrej Mitrovic  
<andrej.mitrovich at gmail.com> wrote:

> import std.stdio;
> import std.string;
>
> void main()
> {
>     char* foo = "foo\0".dup.ptr;
>     writefln("Foo: %s", foo);
> }
>
> This will write the address of foo. Often when you link with C code
> you have C structures such as this:
> struct Info
> {
>     char* name;
>     char* info;
> }
>
> I think it would be convenient if writef would call to!string for
> char* parameters behind the scenes if %s is the format specifier.
>
> I mean yes, you can use to!string in your code, or you can write D
> classes that wrap C libraries, but when you're *testing* D code ported
> from C it would be so much more convenient if you can pass a char* to
> writef() and use %s to treat it as a C string without having to go
> through the trouble of writing to!string everywhere.

I feel uneasy with this feature.  Basically, this means writef makes the  
assumption that char * always means zero-terminated string.  But that is  
not necessarily true.  There is a huge problem with this in C, it's called  
buffer overflow errors.  I'd rather you have to be specific when dealing  
with writef, it would be too easy to get back into buffer overflow hell.

That being said, there should be an easy way to create a char array from a  
zero-terminated string *without* allocation.  Essentially, you need to do  
strlen on the string, and then convert to an array.  This is superior to  
to!string since you do not need to make a copy of the data (especially if  
just printing it, that would be a waste).

I don't know if such a thing exists, it definitely would be a useful thing  
I think.

-Steve


More information about the Digitalmars-d-learn mailing list