Array length & allocation question

Derek Parnell derek at psych.ward
Mon Jun 12 18:14:27 PDT 2006


On Tue, 13 Jun 2006 01:05:04 +0200, Oskar Linde wrote:

>> Setting the length to zero is a convenient way to reserved RAM for an 
>> array.
> 
> t arr.length = 100_000_000; arr = arr[0..0]; is almost as convenient.

Unfortunately this only appears to reserve the RAM, because the next change
in length will cause a new allocation to be made. See the example program
below ...
 
>> Also consider this ...
>> 
>>     foo("");
>> 
>> Now how can 'foo' be written to detect a coder's error of passing it an 
>> uninitialized array.
>> 
>>     char[] x;
>>     foo(x);
>> 
> 
> Like this:
> 
> void foo(char[] arr) {
> 	if (!arr)
> 		writefln("Uninitialized array passed");
> 	else if (arr.length == 0)
> 		writefln("Zero length array received");
> }

Yes, I can see that D can now distinguish between the two. This didn't used
to be the case, IIRC. However there is still a 'bug' with this as the
program here demonstrates...


 import std.stdio;
 void main()
 { 

    char[] arr;

    foo(arr);
    foo("");
    foo("".dup);

    writefln("%s %s", arr.length, arr.ptr);
    arr.length = 100;
    writefln("%s %s", arr.length, arr.ptr);
    arr = arr[0..0];
    writefln("%s %s", arr.length, arr.ptr);
    arr.length = 50;
    writefln("%s %s", arr.length, arr.ptr);
    arr.length = 500;
    writefln("%s %s", arr.length, arr.ptr);
 
 }

 void foo(char[] t)
 {
    writefln("foo: %s %s", t.length, t.ptr);
 }

The results are ...
foo: 0 0000
foo: 0 413080
foo: 0 0000  *** A 'dup'ed empty string is now a null string.
0 0000
100 8A2F00
0 8A2F00   *** RAM appears to be reserved.
50 8A1F80  *** But it is not as a new allocation just occurred.
500 8A3E00 *** This allocation is expected.

-- 
Derek
(skype: derek.j.parnell)
Melbourne, Australia
"Down with mediocrity!"
13/06/2006 11:08:24 AM



More information about the Digitalmars-d-learn mailing list