1

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. 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.

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?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Zhi
  • 61
  • 3

2 Answers2

5

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).

John3136
  • 28,809
  • 4
  • 51
  • 69
2

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).

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278