G++ Compiler returning the same address of a variable after every run ( even after name changes )

Viewed 201

My assumption is that compiler changes the address of the variable after every run. (And it does in MSVC)

For some reason, G++ Compiler for me returns the same address every time I run.

  1. Even after closing and running again, it returns the commented address. Is there any optimization technique I am unaware of?
  2. After changing variable names too, this returns the same address.

Want to understand the difference between MSVC and G++ and the reason behind it.

#include<iostream>
using namespace std;

int main(){
   int b[] = {23,4,6,1,5,7,8,7};
   cout << b; //0x61fef0
   cout << endl;
   cout << &b[0]; //0x61fef0

   return 0;

}

Note: I am using g++ (MinGW.org GCC Build-2) 9.2.0

2 Answers

When a compiler compiles an object file, all addresses are relative. The linker then takes all these addresses and puts them into their right place. By right place, I mean where the operating system expects them to be. (Details are determined by platform dependent linker script)

When you load an executable, the operating system will place both your code (the .text section in ELF) and the data (.data and .bss sections in ELF) at the correct address and then branch to those addresses.

In a program branch (goto) addresses in an executable can either be fixed or relative (position independent). If they are fixed, typically an executable use the same addresses. If they are relative, the operating system can load to executable to any address, it will then have to set up extra trampoline code to work correctly.

For security operating system use Address Space Layout Randomization (ASLR). In this mode the operating system will randomize where stuff is loaded. This make it harder to exploit security holes. How exactly this works is platform dependent.

As far as I know Linux on x86 uses fixed addresses unless you build your allocation with -PIE (position independent executable.

Hope that this gives you a better idea of what is going on.

Compiler allocates memory from the available free memory pool. Computers usually maintain a list of free and used memory. So, you will get the same address after every compilation. Thus, even after changing variable naem, you are getting same memory address.

Related