3 ms·
The OS will initialize the memory of the stack to 0 before the program starts. But before main is called, the compiler is free to insert other code that runs be
by Buge 11y ago
The OS will initialize the memory of the stack to 0 before the program starts. But before main is called, the compiler is free to insert other code that runs before main. gcc inserts a function named __libc_start_main that runs before main. This code will modify the content of the stack. So when main is run, the stack where the uninitialized local variable is has a decent chance of not being 0 anymore.
This is easily testable.
#include <stdio.h>
int main(void) {
char* pointers[20];
int i;
for (i = 0; i < 20; ++i) {
printf("%p\n", pointers[i]);
}
return 0;
}
And yes when I run it, most of the pointers are not null.
- exDM69 11y agoSure, the C runtime initialization runs before main. Unless you're looking at the stack at _start, it's probably unintialized. And it depends on your libc implementation, etc. It just happened to be zero in the author's case.
- kalmar 11y agoOh this is cool! I should have checked more pointers. On my machine, the single pointer was always null, and I read up on stack being initialized to zero. I didn't realize the things-before-main could mess up the stack so much.