As far as I know, malloc does not initialize the allocated memory. However, on macOS arm64, all values appear as zero. Why does this phenomenon occur? Is this related to ASLR?
#include <stdio.h>
#include <stdlib.h>
int main(int argc, const char * argv[]) {
int *ptr = malloc(sizeof(int) * 100);
for (int idx = 0; idx < 100; idx++) {
printf("%d\n", ptr[idx]); // 0
}
free(ptr);
return 0;
}
(lldb) memory read 0x126004f70 --size 4 --count 100 -f d
0x126004f70: 0
0x126004f74: 0
0x126004f78: 0
0x126004f7c: 0
0x126004f80: 0
0x126004f84: 0
0x126004f88: 0
0x126004f8c: 0
0x126004f90: 0
0x126004f94: 0
0x126004f98: 0
0x126004f9c: 0
...
calloc. it might have happened even beforemallocwas called: MSVC typically provides a C executable with 2GB of memory for code, stack, heap, everything, and some other implementation might zero the lot before execution begins.printf("%d\n", ptr[idx]);withprintf("0\n");(or any number) if it wants to - even if the memory returned bymalloccontains indeterminate values.mallocs most of the memory: it is all0. How tragic if it reveals personal data or activity from previous usage. It's a C requirement only, for efficient code.