please correct my char count program...

davidl davidl at 126.com
Mon Jul 2 20:06:49 PDT 2007


It's really bad to teach someone write buffer overflow vulnerable code

>
> import std.stdio : readln, writef, writefln;
>
> void main()
> {
>     writef("Please input your text: ");
>     auto s = readln();
>     writefln("Your text length is: %s", s.length);
> }
>
> Note that strings in D are *not* NUL-terminated like they are in C.
> Your code wouldn't work since the .length of a char[100] is *always*
> 100.  The following is untested, but should work:
>
> import std.string : toString;
>
> void main()
> {
>     char[100] c_string_buffer;
>     scanf("%s", c_string_buffer.ptr);
>     auto d_string = toString(c_string_buffer.ptr);
> }
>
> .ptr gives you a pointer to an array's first element, so (char[100]).ptr
> is a char*.
>
> In this case, toString(char*) assumes its argument is a C-style
> NUL-terminated string, and converts it to a D string.  Note that it will
> return a slice of the input data, so that in this particular case,
> d_string must not outlive c_string_buffer.
>
> 	-- Daniel



-- 
使用 Opera 革命性的电子邮件客户程序: http://www.opera.com/mail/


More information about the Digitalmars-d-learn mailing list