Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

c - Kernel zeroes memory?

I am using Debian squeeze and have noticed that memory is always zeroed. Is this new in linux distributions ? Some time ago, I believe I could use puts() and garbage would be output.

I run this test program many times but the commented results are always the same. (I have randomize_va_space=2 in sysctl.conf so I know that memory in different locations is being used at each run.)


char *a = malloc(50000000);
a[49999999] = '';
puts(a); // it outputs nothing since all are zeroes
printf("%p
", a);
if(a[5000] == '') // this condition is always true
{
    puts("It is a nul char.");
}

Is it possible to make the system not zero memory ? What options could this Debian squeeze installation have activated that always zero memory ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

On any modern operating system, the only way newly obtained memory will contain nonzero values is if memory previously freed by your program got reused by malloc. When new memory is obtained from the operating system (kernel), it is initially purely virtual. It has no physical existence; instead it is mapped as copy-on-write mappings of a single shared memory page that's full of 0 bytes. The first time you attempt to write to it, the kernel will trap the write, allocate a new page of physical memory, copy the contents of the original page (which in this case are all 0 bytes) to the new page, and then resume your program. If the kernel knows the newly allocated physical memory is already zero-filled, it might even be able to optimize out the copy step.

This procedure is both necessary and efficient. It's necessary because handing over memory that might contain private data from the kernel or another user's processes to your process would be a critical security breach. It's efficient because no zeroing is performed at allocation time; the "zero-filled" pages are just reference to a shared zero page.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...