I was writing some code in XCode and noticed something interesting when I was partially filling an array. My code was basically something like this (this is just an example for the sake of simplicity):
#include <iostream>
using namespace std;
int main(){
int** array = new int*[20];
for(int k = 0; k < 20; k+=3){
array[k] = &k;
}
for(int k = 0; k < 20; k++){
bool ptrVal = (array[k] == nullptr);
cout << k << ": " << ptrVal << endl;
}
}
This snippet of code ended up printing out this:
0: 0
1: 0
2: 0
3: 0
4: 0
5: 0
6: 0
7: 1
8: 1
9: 0
10: 1
11: 1
12: 0
13: 1
14: 1
15: 0
16: 1
17: 1
18: 0
19: 1
I was expecting this:
0: 0
1: 1
2: 1
3: 0
4: 1
5: 1
6: 0
7: 1
8: 1
9: 0
10: 1
11: 1
12: 0
13: 1
14: 1
15: 0
16: 1
17: 1
18: 0
19: 1
Afterwards I read the article below about how the OS is overcommitting memory: C++ memory allocation for an array of pointers
Does the OS deliberately allocate non-contiguous blocks of memory for an array of pointers that has been partially filled? If so why does it do this and what could be the reasons for the results shown in my sample code?