简体   繁体   中英

Zero RAM using C in Linux

How can I zero unused RAM in Linux for security purposes ? I wrote this simple C program but I do not know if the RAM called by malloc will be reused at the next loop or if new RAM will be used. Hopefully, after a few minutes the entire RAM will have been zeroed.

#include <unistd.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    char *a = NULL; // declare variable

    while(1) // infinite loop
    {
        a = malloc(524288); // half a MB
        memset(a, 0, 524288); // zero
        free(a); // free

        sleep(1); // sleep for 1 second
    }
}

Linux already has a kernel process that is zeroing memory using idle cycles so it will have memory ready to hand to processes that request it.

Your loop may or may not zero different memory depending on the particular malloc implementation. If you really want to write a process like you describe, look into using sbrk directly to ensure you're cycling memory in and out of your process. I bet if you check you'll find every byte given to you by sbrk is already zero, though.

You can't zero system RAM. The system owns it. If you want to run a system which zeros the RAM then you need to write your own OS!

As long as you never access uninitialized memory, you don't have to worry about what someone else left behind. As long as you never free memory before zeroing it out, you don't have to worry about what you have left behind.

I think you need to write a kernel module to actually do this reliably. And then you still could only zero unused pages. Note that pages that were used by other processes will be cleared automatically by the kernel on allocation.

What are you trying to do? Avoid cold boot attacks?

Typically, on my system (2.6.36) I can free all the unused (but allocated) memory by just doing a while(1) malloc(); loop, and killing it when it stops allocating memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM