static array crashes my program

John Colvin via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Dec 5 05:09:07 PST 2015


On Saturday, 5 December 2015 at 09:49:06 UTC, ref2401 wrote:
> I want to create a static array large enough to store 1MB of 
> float values.
> What am I doing wrong?
> Here is a sample code with notes:
>
> void main(string[] args) {
> 	enum size_t COUNT = 1024 * 512 / float.sizeof; // works OK :)
> 	//enum size_t COUNT = 1024 * 512 * 2 / float.sizeof; // 
> constantly crashes :(
> 	float[COUNT] arr;
> 	writeln(arr.length);
> }
>
> DMD: 2069.2
> OS: Win 8.1 Pro

The default stack size is probably 1MB, which means your 1MB 
array plus a few local variables is too much. Arrays that large 
should be allocated on the heap in most circumstances.

Watch out for this:
static assert(is(typeof(new float[3]) == float[]));
because `new T[n]` is a special case in the grammar. If you 
really must have a static array on the heap (as opposed to a 
dynamic array / slice T[]), you can use something like this, but 
i wouldn't recommend it:

T[N]* heapStaticArray(T, size_t N)()
{
     return cast(T[N]*)((new T[N]).ptr);
}

void main()
{
	int[4]* a = heapStaticArray!(int, 4)();
	(*a)[] = 3;
}


More information about the Digitalmars-d-learn mailing list