Deallocate array?

Ali Çehreli acehreli at yahoo.com
Thu May 9 19:14:41 PDT 2013


On 05/09/2013 05:58 PM, Matic Kukovec wrote:

 > Hi again Steve, or anyone else whose reading this.
 > I was playing around with D and C# and need help getting this array
 > stuff to work.

[...]

 > My question is what is how do i get the same C# functionality in D
 > without running out of memory and preferably without using the GC 
directly?
 >
 > I'm running Windows Vista 64bit, DMD 2.062 fresh install, compiling with
 > "-m32" flag.

You have a string array of 100_000_000 elements. (You can insert 
underscores in literals to make code more readable.)

On a 32-bit system string is 8 bytes (e.g. by pragma(msg, 
string.sizeof)). So you have a single array of 800 million bytes. Then, 
each of those strings point at 22 bytes of individully allocated memory 
areas.

Note that 800 million is about 20% of the entire addressable memory of 
that system. If you have a single value that happens to look like a 
pointer into that memory, that huge block will remain in memory forever. 
The funny thing about dmd's current conservative GC is that even an 
integer can be mistaken to be a pointer into that memory.

So that's the problem today.

I don't know the exact requirement here but if you really must have 100 
million strings at one time, then you may want to do your own memory 
management. The following should work:

import std.stdio;
import core.memory;

void main()
{
     enum size_t times = 10;
     enum size_t stringCount = 100_000_000;

     foreach (i; 0 .. times) {
         auto rawMemory = cast(string*)GC.calloc(string.sizeof * 
stringCount);

         // D's cool feature of making a slice from raw pointer
         auto tempArray = rawMemory[0 .. stringCount];

         foreach (ref s; tempArray) {
             s = "aaaaaaaaaaaaaaaaaaaaa";
         }

         GC.free(rawMemory);
         // You may want to set tempArray to null at this point to prevent
         // using it accidentally but it is not necessary.

         writefln("Done with allocation %s/%s; please press Enter",
                  i + 1, times);
         readln();
     }
}

Ali



More information about the Digitalmars-d-learn mailing list