为什么我可以通过指针强制转换来更改局部 const 变量,而不是 C 中的全局变量? [英] Why can I change a local const variable through pointer casts but not a global one in C?

查看:19
本文介绍了为什么我可以通过指针强制转换来更改局部 const 变量,而不是 C 中的全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用指针改变一个常量的值.

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"函数级变量放入只读内存中,因为它位于堆栈中,它必须位于可读写页面上.但是,编译器/链接器会看到您的 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.

这篇关于为什么我可以通过指针强制转换来更改局部 const 变量,而不是 C 中的全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆