Issue
Why does linux not allocating physical RAM if I try to make pages dirty with only wirte, but does allocates if I do read and write?
Got some code for linux 5.4 and aarch64. Compiler is gcc 6.3.1
int main(int argc, char *argv[])
{
long size;
long size_bytes;
char *ptr;
size = strtol(argv[1], NULL, 0);
size_bytes = size * 1024 * 1024;
ptr = malloc(size_bytes);
if (!ptr)
goto exit;
// Make memory dirty so it is allocated in real RAM
for (int i = 0; i < size_bytes; i += sysconf(_SC_PAGESIZE))
ptr[i] += 1; // works ok
//ptr[i] = 1; // does not allocates physical RAM
while(1)
sleep(1);
exit:
free(ptr);
return 0;
}
Solution
ptr[i] = 1;
You do not use ptr
so the compiler is optimizing it out. There is not write operation.
Change the char *ptr
to volatile char *ptr
and the compiler will not optimize it out.
Answered By - gulpr Answer Checked By - Senaida (WPSolving Volunteer)