深入理解const
来源:互联网 发布:好的英语听力软件 编辑:程序博客网 时间:2024/05/22 07:42
#include <stdio.h>#define PRINT(e) printf("%s=%d\n",#e,e) const int a ; //in BSS uninitialized data sectionconst int b = 2; //in read only data sectionint * p = NULL ; int main(){ const int c ; //in stack,can be modified by pointer const int d = 4; //in stack p = (int*)&a; *p = 111; //OK,because a in BSS; PRINT(a); //p = (int*)&b; //*p = 222; //Segmentation fault (core dumped),b in readonly data section //PRINT(b); p = (int*)&c; *p = 333; //c in stack PRINT(c); p = (int*)&d; *p = 444; //d in stack PRINT(d); return 0;}
1. const 变量不能直接被修改,在编译时就被编译器限定;
2. 未初始化的全局const int a 位于BSS段,可以通过指针来改变;
3. 初始化过的 全局 const int b 位于只读数据段,通过指针在运行时修改会造成内存访问失败;
4. 放在stack中的局部const变量c,d可以通过指针修改。
同样,类似的还有全局和局部的static变量,只要能够获得变量的地址,就能使其在模块外或函数外部被访问修改。
附:
程序用GCC 编译后 nm 导出的部分符号表:
0000000000400630 R _IO_stdin_used
0000000000400638 R __dso_handle
0000000000400640 R b
0000000000400720 r __FRAME_END__
0000000000600728 t __frame_dummy_init_array_entry
0000000000600728 t __init_array_start
0000000000600730 t __do_global_dtors_aux_fini_array_entry
0000000000600730 t __init_array_end
0000000000600738 d __JCR_END__
0000000000600738 d __JCR_LIST__
0000000000600740 d _DYNAMIC
0000000000600918 d _GLOBAL_OFFSET_TABLE_
0000000000600940 D __data_start
0000000000600940 W data_start
0000000000600944 A __bss_start
0000000000600944 A _edata
0000000000600948 A __TMC_END__
0000000000600948 b completed.6094
0000000000600950 B p
0000000000600958 B a
0000000000600960 A _end
- 深入理解const
- 深入理解const
- 深入理解const
- const 深入理解
- 深入理解const char
- 深入理解const
- 深入理解const
- const关键字的深入理解
- const关键字的深入理解
- 深入理解c++中const的奥秘
- 深入理解C++的const变量
- 深入理解C语言中的const
- 深入理解C++的const变量
- 深入理解C++函数重载const
- 深入理解const char*p,char const*p,char *const p,const
- 深入理解const char*p,char const*p,char *const p,const char **p,char *const*p ...
- [转]深入理解const char*p,char const*p,char *const p,const char **p,char const**p,cha ...
- 《c专家编程》笔记--深入理解const char*p,char const*p,char *const p
- Safari on iOS 支持的4种Meta Tags
- 怎样开启Win7快速启动栏
- subquery(nested query)可以使用主查询中的FROM列出的表中的列
- Android 中LayoutInflater的使用!
- Hibernate中用hql查询部分字段 可解决异常java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to
- 深入理解const
- JavaScript数据库 Taffy DB
- 深入理解const char*p,char const*p,char *const p,const char **p,char const**p,char *const*p,char**const p
- X64 Linux 无法从本地字符界面登陆
- Android程序的Unable to instantiate activity ComponentInfo异常
- 10304Optimal Binary Search Tree
- WCF 跨域 Http绑定
- 多项分布的最大似然估计
- Microsoft.Jet.OLEDB.4.0 在 64 bit 主機使用