为什么我可以改变通过指针蒙上了局部变量常量而不是一个全球性的一个是C? [英] Why can I change a local const variable through pointer casts but not a global one in C?

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

问题描述

我想用指针来改变一个恒定值。

I wanted to change value of a constant by using pointers.

考虑以下code

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.

但是当我试图在同一code。与一个全局常量,我得到以下运行时错误。
在Windows崩溃记者开放。

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;"

考虑以下code

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;
}

此程序被编译在​​$ C $个cblocks IDE的MinGW环境。

This program is compiled in mingw environment with codeblocks IDE.

任何人能解释这是怎么回事?

Can anyone explain what is going on?

推荐答案

这是在只读存储器!

基本上,你的电脑解析虚拟到使用两级页表系统的物理地址。随着认为,盛大的数据结构来一个特殊的位重presenting一个页面是否是可读的。这是有帮助的,因为用户进程可能不应该超过书写自己的组件(尽管自修改code是挺酷的)。当然,他们大概也不宜过度书写自己的常数变量。

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.

您不能把一个常量功能级变量为只读存储器,因为它生活在栈,它必须是一个读写页。但是,编译器/连接器看到你的常量,并把它在只读存储器(它是常量)帮你的忙。显然,覆盖将导致谁取出来的过程中,愤怒通过终止其内核的各种不快。

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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