When a process requests for memory and an operating system is giving some new pages to the process, the kernel should initialize the pages (with zeros for instance) in order to avoid showing potentially confident data that another process used. The same when a process is starting and receives some memory, for example the stack segment.
When I execute the following code in Linux, the result is that the majority of allocated memory is indeed 0, but something about 3-4 kB at the bottom of the stack (the last elements of the array, the highest addresses) contains random numbers.
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
int * a = (int*)alloca(sizeof(int)*2000000);
for(int i = 0; i< 2000000; ++i)
cout << a[i] << endl;
return 0;
}
- Why isn't it set to zero too?
- Could it be because it is being reused by the process?
- If yes, could it be the initialization code that had used those 3-4 kB of memory earlier?