问题描述
我想通过使用指针来改变常量的值.
I wanted to change value of a constant by using pointers.
考虑下面的代码
int main()
{
const int const_val = 10;
int *ptr_to_const = &const_val;
printf("Value of constant is %d",const_val);
*ptr_to_const = 20;
printf("Value of constant is %d",const_val);
return 0;
}
正如预期的那样,常量的值被修改了.
As expected the value of constant is modified.
但是当我使用全局常量尝试相同的代码时,出现以下运行时错误.Windows 崩溃报告器正在打开.在此语句*ptr_to_const = 20;"中打印第一个 printf 语句后,可执行文件停止运行
but when I tried the same code with a global constant, I am getting following run time error.The Windows crash reporter is opening. The executable is halting after printing the first printf statement in this statement "*ptr_to_const = 20;"
考虑下面的代码
const int const_val = 10;
int main()
{
int *ptr_to_const = &const_val;
printf("Value of constant is %d",const_val);
*ptr_to_const = 20;
printf("Value of constant is %d",const_val);
return 0;
}
这个程序是在 mingw 环境下用 codeblocks IDE 编译的.
This program is compiled in mingw environment with codeblocks IDE.
谁能解释一下这是怎么回事?
Can anyone explain what is going on?
推荐答案
它在只读内存中!
基本上,您的计算机使用两级页表系统将虚拟地址解析为物理地址.伴随着庞大的数据结构而来的是一个特殊的位,表示页面是否可读.这很有帮助,因为用户进程可能不应该重写他们自己的程序集(尽管自修改代码有点酷).当然,他们可能也不应该重写自己的常量变量.
Basically, your computer resolves virtual to physical addresses using a two level page table system. Along with that grand data structure comes a special bit representing whether or not a page is readable. This is helpful, because user processes probably shouldn't be over writing their own assembly (although self-modifying code is kind of cool). Of course, they probably also shouldn't be over writing their own constant variables.
您不能将const"函数级变量放入只读内存中,因为它位于堆栈中,并且必须位于读写页面上.但是,编译器/链接器会看到您的常量,并通过将其放入只读内存(它是常量)来帮助您.显然,覆盖会导致内核的各种不满,内核将通过终止进程来消除对进程的愤怒.
You can't put a "const" function-level variable into read only memory, because it lives in the stack, where it MUST be on a read-write page. However, the compiler/linker sees your const, and does you a favor by putting it in read only memory (it's constant). Obviously, overwriting that will cause all kinds of unhappiness for the kernel who will take out that anger on the process by terminating it.
这篇关于为什么我可以通过指针转换更改局部常量变量,而不是 C 中的全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!