Reputation: 88
I just want to make it clear to myself about memory allocation (if that's how I may call it correctly) in c on x64 architecture.
I have one program that simply outputs the location of the variable in the memory. I run it several times and then I see some strange thing going on:
The line of code:
printf("[*] test_val @ 0x%016llx = %d 0x%016llx\n", &test_val, test_val, test_val);
1st time:
[*] test_val @ 0x00005612f1edb050 = -72 0x00000000ffffffb8
2nd time:
[*] test_val @ 0x000055ec3b64f050 = -72 0x00000000ffffffb8
3rd time:
[*] test_val @ 0x00005577e99d4050 = -72 0x00000000ffffffb8
It seems that the memory location of the variable test_int
is different every time except for the first 2.5 bits (00005) and the last 1.5 bits (the 050 part doesn't change).
There would've been no question, but in the book I'm learning by this address is constant all the time. The main difference is that this book is about 32bit architecture.
Do I understand correctly that the memory is being allocated dynamicly in x64 systems? Is there any way to "predict" where will the variable be, considering the fact that we know last 1.5 bits, 050 in this case?
Upvotes: 1
Views: 469
Reputation: 21617
You don't specify the operating system. However, it has become common for operating systems to load applications at random locations in memory. Compilers and linkers have produced relocatable code for decades but historically this was done to allow shared libraries to be loaded in different locations from different programs.
Now operating systems are loading the program at different locations. This is done as a security measure. The objective is to prevent crackers from manipulating specific memory locations.
The reason the last few bits of the address is the same is because the program is aligned on page boundaries.
Upvotes: 0
Reputation: 21542
There would've been no question, but in the book I'm learning by this address is constant all the time.
If this book actually claimed that addresses are to remain constant throughout multiple runs of the same program, it was wrong. In fact, even during the same run of one program, local variables with automatic storage duration might get different addresses throughout multiple calls in the same running instance. Consider:
void foo()
{
volatile int a = 12345;
printf("%p\n", (void *)&a);
}
void bar()
{
printf("In bar\n");
foo();
}
int main()
{
foo();
bar();
return 0;
}
I get the output:
00B6FE58
In bar
00B6FE54
This is because the call to bar
creates another frame on the stack when foo
is entered, giving a
a different address. In general, the only thing that is safe to reason about, I believe, is if a variable has static storage duration, its address should remain constant throughout a single run of a program.
As for why you're observing different addresses when running your program multiple times, that's because:
Upvotes: 2