Q:

Memory use keep increasing in for loop while using dynamic array.(C++)

The following is my C++ code.
I found the memory use will keep increasing if I try to use test1 array to calculate anything.
double **test1;
test1=new double *[1000];

for(int i=0;i<1000;i++){
    test1[i]=new double [100000000];
    test1[i][0]=rand() / (double)RAND_MAX*100;
}

for(int j=1;j<100000000;j++){
    for(int i=0;i<1000;i++){
        test1[i][j]=test1[i][j-1];  //this cause memory use increase.
    }
}

If I delete the line.
test1[i][j]=test1[i][j-1];

The memory use will become a small constant value.
I thought I have already declare the dynamic array at the first part, the memory use should be a constant if I didn't new any array.
What cause the memory use increasing? And how do I avoid it?
(I use linux command "top" to monitor the memory use.)

A:

In the first loop you create 100,000,000 doubles, which is 800 MB of allocation.  You write to the first one only.
Later you write to the rest.  When you do this, the operating system needs to actually give you the memory to write into, whereas initially it just gave you a mapping which would page fault later (when you write to it).
So basically, since each allocation is so large, the memory required to back it is not physically allocated until it is used.
The code is nonsensical, because eventually you try to write to 800 GB of memory.  I doubt that will ever complete on a typical computer.

