Fixing "toStringz"

Andrej Mitrovic andrej.mitrovich at gmail.com
Wed Aug 21 03:43:27 PDT 2013


On 8/21/13, monarch_dodra <monarchdodra at gmail.com> wrote:
> I'm looking for ideas though on being able to detect
> if a string *is* a manifest constant string?

I've proposed once to allow declaring an enum parameter, e.g.:

void foo(enum string input) { }

This would only allow foo to be called with a manifest constant (e.g.
a string literal). This way you could overload functions and perform
optimizations in some overloads.

Note that we already have a special way to e.g. mark a function to
only take a null literal, by making the parameter "typeof(null)". But
using typeof("") wouldn't quite work here, so if there's a language
enhancement to be made I'm in favor of the enum approach.

Btw this thread has already popped up before, e.g.:
http://forum.dlang.org/thread/j0ie3e$18mh$1@digitalmars.com where I
showed the problem of toStringz:

-----
import std.string;
import std.stdio;

struct A
{
    immutable char[2] foo;
    char[2] bar;
}

void main()
{
    auto a = A("aa", "\0b");   // embed \0 in the second field

    // toStringz picks up \0 from the 'bar' field, does not allocate
    auto charptr = toStringz(a.foo[]);

    a.bar = "bo";  // remove embedded \0 from second field
    printf(charptr);  // prints two chars and then garbage
}
-----

Couldn't this also have security issues? I think we definitely have to
fix toStringz, the look-ahead for \0 is an over-reaching optimization,
and at best it should be selectable behavior in the same way as we
have assumeUnique for arrays.


More information about the Digitalmars-d mailing list