简体   繁体   English

为什么内核不清除进程中第二个 malloc 分配的内存?

[英]Why doesn't kernel clear the memory allocated by second malloc in a process?

Follow these two questions:请遵循以下两个问题:

  1. Kernel zeroes memory?内核将内存归零?

  2. If the heap is zero-initialized for security then why is the stack merely uninitialized?如果为了安全起见对堆进行零初始化,那么为什么堆栈只是未初始化?

#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>

const size_t n = 4;
const size_t m = 0x10;

int main()
{
        int *p = malloc(m*sizeof(int));
        printf("%p ", p);
        for (size_t i = 0; i < m; ++i) {
            printf("%d", p[i]);
        }
        printf("\n");

        memset(p,9,m*sizeof(int));
        free(p);

        int *v = malloc(m*sizeof(int));
        printf("%p ", v);
        for (size_t j = 0; j < m; ++j) {
            printf("%x", v[j]);
        }

        printf("\n");
        return 0;
}

OUTPUT:输出:

0xaaaae7082260 0000000000000000
0xaaaae7082260 0090909099090909909090990909099090909909090990909099090909909090990909099090909909090990909099090909

I have a question: In a process, the assigned memory by malloc is set 0 when first using malloc .我有一个问题:在一个进程中,首次使用malloc时, malloc分配的内存设置为 0 。 But reusing malloc to allocate a new memory after free the first assigned memory, the new memory has the same virtual address and same content with the first memory.但是在free第一个分配的内存后,重新使用malloc分配新内存,新内存与第一个内存具有相同的虚拟地址和相同的内容。

My question: How does the kernel know that the memory is first assigned to a process and is needed to be set zero?我的问题:内核如何知道内存首先分配给进程并需要设置为零?

And how does the kernel know that the memory is reassigned to the same process and doesn't need to be cleared?内核怎么知道内存被重新分配给了同一个进程,不需要清除?

Getting a chunk of memory from the OS for your memory pool and reusing memory already in your memory pool are two different things.从操作系统为内存池获取一块内存和重用内存池中已有的内存是两件不同的事情。

The OS may zero the memory when you first get it but it is up to the "malloc" implementation whether it zeros memory (either on free or malloc).操作系统可能会在您第一次获取内存时将其清零,但是否将内存清零(在 free 或 malloc 上)取决于“malloc”实现。

The answer to "how does the kernel know that the memory is first assigned to a process" is that the process (via the C library) makes a request to the kernel to allocate it some memory, so the kernel knows that the memory should not reveal its previous contents (and zeroing the allocated memory is one way of ensuring that information does not leak between processes). “内核如何知道内存首先分配给进程”的答案是进程(通过 C 库)向内核请求为其分配一些内存,因此内核知道该内存不应该揭示其先前的内容(并将分配的内存归零是确保信息不会在进程之间泄漏的一种方法)。

The answer to "how does the kernel know that the memory is reassigned …" is "it doesn't" — that information is private to the process and the kernel has no knowledge of what the process does to reuse the memory. “内核如何知道内存被重新分配……”的答案是“它不知道”——该信息是进程私有的,内核不知道进程如何重用内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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