简体   繁体   中英

C++ memory, allocation

Since first and last address are same or the address in &pi and a are same, is the address in a is from constant data segment or free store area?

int main() 
{
    const int pi = 10;

    cout <<"This is constant memory area's address " << &pi << endl; 

    int *a = new int;

    cout << "This is free store memory area's address " << a << endl;

    a = (int*) &pi;
    cout << *a << endl;
    cout << "This is free store memory area's address " <<a << endl;

    return 0; 
}   

Your concepts are not correct. There are side effects or limitations in your program.

The statement:
const int pi = 10;

Declares a constant. The compiler can put the constant wherever it wants.
Here are some possible locations:

  1. Directly into the processor's instruction (when the value is used).
  2. The compiler can place the value into a data area in the executable section.
  3. In a register (registers are usually not addressable, have no address).
  4. In a constant data area of your program.
  5. The heap.
  6. The stack.
  7. The global variable area.

However, the moment you take the address of the constant, the compiler cannot store the value in these places:

  1. Register (registers are not pointer accessible).
  2. In executable instructions, eg move reg_a, #10

Also, pointers can live in registers too. However, taking the address of a pointer prevents the pointer from living in a register, since using the & operator requires that the variable live in an addressable memory location and registers are not addressable via pointer.

BTW, you have a memory leak:

a = new int;
a = &pi;

The last statement looses or leaks the location of the dynamically allocated integer.

Note: There are some processors in which registers live in an addressable location in memory; but these are exceptions.

Edit 1: Symbol Tables
When you declare a variable as const and assign it a literal, the compiler can store the variable in a table of <symbol, value> and not take up any variable space in the program.

When the compiler encounters the symbol, eg pi , it can look up the symbol, pi , in its table and substitute the value (10). So the expression:
int b = pi;
will become, after substitution:
int b = 10;
Thus your pi variable doesn't have any allocated space, in your program . In the above example, the value of the variable is placed into your program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM