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] = '\0';
puts(a); // it outputs nothing since all are zeroes
printf("%p\n", a);
if(a[5000] == '\0') // 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 ?
The Windows kernel-mode memory manager component manages physical memory for the operating system. This memory is primarily in the form of random access memory (RAM). The memory manager manages memory by performing the following major tasks: Managing the allocation and deallocation of memory virtually and dynamically.
No, Linux does not zero its menory after releasing it. Most libraries implement zeroing the memory while allocating it, but this is programming language dependent and can be overridden.
The kernel has full access to the system's memory and allows processes to safely access this memory as they require it. Often the first step in doing this is virtual addressing, usually achieved by paging and/or segmentation.
Linux provides a variety of APIs for memory allocation. You can allocate small chunks using kmalloc or kmem_cache_alloc families, large virtually contiguous areas using vmalloc and its derivatives, or you can directly request pages from the page allocator with alloc_pages .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With