Follow these two questions:
#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?