函数中声明的const变量在堆栈中是否有只读存储器? [英] Is there a read only memory in the stack for const variable declared in a function?

查看:71
本文介绍了函数中声明的const变量在堆栈中是否有只读存储器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道全局const存储在.rodata中

I know global const is stored in .rodata

此外,我知道在函数中声明的变量存储在堆栈中.但是,由于const应该是只读的,因此在堆栈中是否有针对它们的特殊部分?如何控制对他们的访问?

Also, I know variables declared in functions are stored in the stack. However since const is supposed to be only read only, is there a special section in stack for them? how are accesses to them controlled?

推荐答案

您应该真正了解的内容:如果将一个对象声明为const,则编译器不会轻易让您尝试对其进行修改,并且如果您避开了编译器,则任何修改对象的尝试都是未定义的行为.而已.没有其他的.忘记.rodata或您学到的任何东西,重要的是尝试修改const对象是未定义的行为.

What you really should know: If an object is declared as const, the compiler will not easily let you attempt to modify it, and if you get around the compiler, then any attempt to modify the object is undefined behaviour. That's it. Nothing else. Forget about .rodata or anything you learned, what counts is that an attempt to modify a const object is undefined behaviour.

我的意思是编译器不允许您使用"并解决该问题:

What I mean by "the compiler doesn't let you" and getting around it:

const int x = 5; 
x = 6; // Not allowed by compiler
int* p = &x; *p = 6; // Not allowed by compiler
int* p = (int*)&x; *p = 6; // Allowed by compiler, undefined behaviour.

执行最后一条语句可能会崩溃,或者将x更改为6,或者将x更改为999,或者使x保持不变,或者使其表现为精神分裂症,在某些时候为5,在其他时候为6,包括x == x为假.

Executing the last statement can crash, or change x to 6, or change x to 999, or leave x unchanged, or make it behave in a schizophrenic way where it is 5 at some times and 6 at other times, including x == x being false.

这篇关于函数中声明的const变量在堆栈中是否有只读存储器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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