When I am declaring some variable outside main then compile stores them in some peculiar way.
int i=1,j=1;
void main(void)
{
printf("%d\n%d",&i,&j);
}
If both i
and j
are not initialized or equals 0 or equals some positive values then they are stored at continuous address spaces in memory whereas if i=0
and j = some +ve integer
then their addresses are separated by fairly large distance.
The problem with is when they are stored on contiguous address spaces it causes some real performance issues like false sharing (have a look here). I've learned that to prevent this, there should be some space between variable's addresses which is automatically provided when i=0
and j=any +ve value
.
Now, what I want to understand is:
- Why the compiler stores variables to noncontinuous addresses only when one initialized to 0 and other initialized to positive values, and
- How can I intentionally do what compiler is doing automatically i.e allocating variables to fairly separated address space.
(Using devcpp gcc 4.9.2)