简体   繁体   中英

How can understand a constant variable in memory. C++

If I have a constant variable, is it stored in a seperate memory space from non-constant variables? I have encounter some odd in this program.

    //--------assign a const value to non-const value-------
const int cst_a = 5;
int* ptra = const_cast<int*>(&cst_a);

cout<<&cst_a<<" "<<ptra<<endl; // same address

*ptra = 6;

cout<<*ptra<<" "<<cst_a<<endl; // same address with different value

//--------assign a non-const value to const value-------

int b = 50;
const int* cst_ptr_b = &b;

cout<<cst_ptr_b<<" "<<&b<<endl; // also same address

b = 55;
cout<<b<<" "<<*cst_ptr_b<<endl; // same address with same value

return 0;

In the first case, &cst_a and ptra has the same memory address, but their value can change seperately. In the second case, cst_ptr_b and &b are also same address, but their value change symetrically. Why?

It may be stored in a memory area that can't be modified. Because of this, your const_cast results in undefined behavior.

Congrats, *ptra = 6; is undefined behaviour. :)
You are not allowed to write to a constant value, not through pointer, not through reference. This is because a constant object might (and most likely will) be put into the constant memory area.

It depends on what value you store in the constant.

const int c = 5; // This will be stored in read only area

Trying to modify read only area is Undefined Behavior (which you have done in your code using const_cast )

Other scenario is,

int i = 5;
const int c = i;  // This is stored in normal read/write memory segment

The problem is the explicit type casting that is taking place in example #1. C++ let's you do this and since const int* and int* are different types along with the compilers free choice to store constants in either writeable or non-writeable memory makes this undefined behaviour, as said in earlier posts.

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