Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why doesn't .net allocate memory when initialize a 2d array?

 var a = new double[7000,7000];

 FillValue(a,3);

It seems .Net doesn't actually allocate any memory to a after executing the first line. Only while it is running the FillValue call does it gradually eat the memory. (which is around 400MB)

Can anyone provide me with more details regarding it? I thought a is filled with 0 after default initialization, how could it take no memory at all?

like image 999
colinfang Avatar asked Oct 23 '12 21:10

colinfang


People also ask

How to allocate memory for 2D array in C?

A 2D array can be dynamically allocated in C using a single pointer. This means that a memory block of size row*column*dataTypeSize is allocated using malloc and pointer arithmetic can be used to access the matrix elements.

How do I malloc a two dimensional array?

Make multiple calls to malloc , allocating an array of arrays. First, allocate a 1D array of N pointers to the element type, with a 1D array of pointers for each row in the 2D array. Then, allocate N 1D arrays of size M to store the set of column values for each row in the 2D array.


2 Answers

There are two ways to 'allocate memory' in Windows: to 'reserve' and to 'commit' memory.

The task manager only shows "Physical Memory Usage History"; the .NET VM apparently uses only reserved memory when you allocate an array, and then goes back and commits the parts that get used.

This way you can reserve memory without actually taking it up, which is more efficient, and reserving memory, according to MSDN, "reserves a range of the process's virtual address space without allocating any actual physical storage in memory or in the paging file on disk". That's why Task Manager doesn't show it.

You can read more about it on the VirtualAlloc page on MSDN.

This is an implementation detail though, so you shouldn't rely on it or anything. The Mono VM, for example, is likely to behave differently.

like image 105
Seth Carnegie Avatar answered Oct 16 '22 15:10

Seth Carnegie


Actually it allocates memory as you can see here:

http://ideone.com/Cd4BR1

Console.WriteLine("Memory before: {0}",GC.GetTotalMemory(true));
var a = new double[5000,5000];
Console.WriteLine("Memory after: {0}",GC.GetTotalMemory(true));

Memory before: 118784 
Memory after: 200224768

( needed to decrease the size of the array to prevent an OutOfMemoryException on ideone )

GC.GetTotalMemory Method

Retrieves the number of bytes currently thought to be allocated.

like image 27
Tim Schmelter Avatar answered Oct 16 '22 16:10

Tim Schmelter