When running the following, it keeps printing the same memory address.
#include <stdio.h>
int array[5] = {2, 4, 6, 8, 10};
int *pointer;
int main()
{
pointer = array;
printf("%p:\t%d\n", pointer, *pointer);
return 0;
}
I don’t know whether this is a problem, but I’m still curious to know why this would be the case, when declaring it within main() would keep returning new addresses.
The reason why you normally get the same address for “array” in the code you posted, but get different addresses if you declare array inside main, is that the array outside main has global scope and so is allocated in a single fixed location, whereas array if declared inside main is allocated on the stack when main is entered (and could conceivably be allocated several times if you called main from elsewhere).
The security feature of randomizing addresses that is described in other answers applies to the stack, not to variables with static duration, because common exploits work by overwriting the stack with hostile code, then jumping to it by overwriting a return address, which is also stored on the stack. Overwriting a non-stack variable with hostile code still leaves the attacker the problem of executing it, and so is a lesser security concern.