Beginner memory question.

WhatMeWorry kheaser at gmail.com
Sat Apr 16 20:41:25 UTC 2022


I'm playing around with dynamic arrays and I wrote the tiny 
program (at bottom). I get the following output:

PS C:\D\sandbox> dmd -m64 maxMem.d
PS C:\D\sandbox> .\maxMem.exe
Reserving 1,610,613,245 elements
reserve() returned a size of: 1,610,613,245
The capacity() of big is 1,610,613,245
ulong.sizeof (num bytes) = 8
Total bytes allocated = 12,884,905,960
Total megabytes allocated = 12,288
Total gigabytes allocated = 12


The discrepancy occurs because my Windows 10 computer only has 
8.0 GB of memory (and that is not even taking the OS into 
consideration).  Are my mega and giga sizes wrong?  Is virtual 
memory entering into the equation?


import std.stdio, std.array, std.algorithm;
import std.format;
import core.exception;

void main()
{
     ulong[] big;

     // reserve returns the new capacity of the array
     ulong e = 1_610_613_245;   // 1_610_613_246 returns out of 
memory error
     writeln("Reserving ", format("%,3d", e) ," elements");
     auto u = big.reserve(e);
	
     writeln("reserve() returned a size of: ", format("%,3d", u) );
	
     writeln("The capacity() of big is ", format("%,3d", 
big.capacity));	
     writeln("ulong.sizeof (num bytes) = ", ulong.sizeof);
     writeln("Total bytes allocated = ", format("%,3d", e * 
ulong.sizeof));

     immutable ulong megabyte = 1_048_576;    // (1024 x 1024)
     immutable ulong gigabyte = 1024 * 1024 * 1024;
	
     writeln("Total megabytes allocated = ", format("%,3d", (e * 
ulong.sizeof)/megabyte));
     writeln("Total gigabytes allocated = ", format("%,3d", (e * 
ulong.sizeof)/gigabyte));
  }


More information about the Digitalmars-d-learn mailing list