Variable Changing Value at the Same Address: Understanding Undefined Behavior
In C , variables with different data types can occupy the same memory address, leading to unexpected outcomes. Consider the following code:
const int a1 = 40; const int* b1 = &a1; char* c1 = (char *)(b1); *c1 = 'A'; int *t = (int*)c1; cout << a1 << " " << *t << endl; cout << &a1 << " " << t << endl;
After running this code, you might expect both a1 and *t to have the value 40, and &a1 and t to have the same address. However, the output is surprising:
40 65 0xbfacbe8c 0xbfacbe8c
How is it possible for a variable at the same address to produce two different values?
Explanation
This behavior occurs due to undefined behavior in the code. Specifically, modifying a const variable like a1 is undefined behavior. The C standard (section 7.1.6.1) explicitly states that any attempt to modify a const object during its lifetime results in undefined behavior.
In this case, by modifying *c1 (which points to a1), we have effectively modified a const variable. This is why the compiler is unable to guarantee the expected behavior, and instead produces unpredictable results.
The possible behaviors in such cases are specified in section 1.3.24 of the standard. These range from ignoring the situation completely to terminating the program with an error message. In this case, the compiler has chosen to produce different values for a1 and *t.
Conclusion
Undefined behavior should be avoided in C code, as it can lead to unexpected and inconsistent results. In this specific scenario, accessing a const variable through a pointer of a different type and modifying it has resulted in undefined behavior and unpredictable output.
The above is the detailed content of Why Does Modifying a `const` Variable Through a Pointer of a Different Type Lead to Undefined Behavior in C ?. For more information, please follow other related articles on the PHP Chinese website!