Why am I able to change the contents of const char *ptr?
http://stackoverflow.com/questions/3228664/why-am-i-able-to-change-the-contents-of-const-char-ptr
I passed a pointer ptr
to a function whose prototype takes it as const
.
foo( const char *str );
Which according to my understanding means that it will not be able to change the contents of ptr
passed. Like in the case of foo( const int i )
. If foo()
tries to chnage the value of i
, compiler gives error.
But here I see that it can change the contents of ptr
easily.
Please have a look at the following code
foo( const char *str )
{
strcpy( str, "ABC" ) ;
printf( "%s(): %s\n" , __func__ , str ) ;
}
main()
{
char ptr[ ] = "Its just to fill the space" ;
printf( "%s(): %s\n" , __func__ , ptr ) ;
foo( const ptr ) ;
printf( "%s(): %s\n" , __func__ , ptr ) ;
return;
}
On compilation, I only get a warning, no error:
warning: passing argument 1 of ‘strcpy’ discards qualifiers from pointer target type
and when I run it, I get an output instead of Segmentation Fault
main(): Its just to fill the space
foo(): ABC
main(): ABC
Now, my questions is
1- What does const char *str
in prototype actually means?
Does this mean that function cannot change the contents of str
? If that is so then how come the above program changes the value?
2- How can I make sure that the contents of the pointer I have passed will not be changed?
From "contents of the pointer" in the above stated question, I mean "contents of the memory pointed at by the pointer", not "address contained in the pointer".
Edit
Most replies say that this is because of strcpy
and C implicit type conversion. But now I tried this
foo( const char *str )
{
str = "Tim" ;
// strcpy( str, "ABC" ) ;
printf( "%s(): %s\n" , __func__ , str ) ;
}
This time the output is, with no warning from compiler
main(): Its just to fill the space
foo(): Tim
main(): Its just to fill the space
So apparently, memory pointed to by str
is changed to the memory location containing "Tim"
while its in foo()
. Although I didn't use strcpy()
this time.
Is not const
supposed to stop this? or my understanding is wrong?
To me it seems that even with const
, I can change the memory reference and the contents of memory reference too. Then what is the use?
Can you give me an example where complier will give me error that I am trying to change a const pointer?
Thanks to all of you for your time and effort.
Your understanding is correct, const char*
is a contract that means you can't change memory through this particular pointer.
The problem is that C is very lax with type conversions. strcpy
takes a pointer to non-const char, and it is implicitly converted from const char*
to char*
(as compiler helpfully tells you). You could as easily pass an integer instead of pointer. As a result, your function can't change content pointed by ptr
, but strcpy
can, because it sees a non-const pointer. You don't get a crash, because in your case, the pointer points to an actual buffer of sufficient size, not a read-only string literal.
To avoid this, look for compiler warnings, or compile, for example, with -Wall -Werror
(if you are using gcc).
This behaviour is specific to C. C++, for example, does not allow that, and requires an explicit cast (C-style cast or a const_cast
) to strip const
qualifier, as you would reasonably expect.
Answer to the extended question
You are assigning a string literal into a non-const char, which, unfortunately, is legal in C and even C++! It is implicitly converted to char*
, even though writing through this pointer will now result in undefined behaviour. It is a deprecated feature, and only C++0x so far does not allow this to happen.
With that said, In order to stop changing the pointer itself, you have to declare it as const pointer to char (char *const
). Or, if you want to make it that both the contents pointed by it and the pointer itself don't change, use a const pointer to const char (const char * const
).
Examples:
void foo (
char *a,
const char *b,
char *const c,
const char *const d)
{
char buf[10];
a = buf; /* OK, changing the pointer */
*a = 'a'; /* OK, changing contents pointed by pointer */
b = buf; /* OK, changing the pointer */
*b = 'b'; /* error, changing contents pointed by pointer */
c = buf; /* error, changing pointer */
*c = 'c'; /* OK, changing contents pointed by pointer */
d = buf; /* error, changing pointer */
*d = 'd'; /* error, changing contents pointed by pointer */
}
For all error lines GCC gives me "error: assignment of read-only location".
Why am I able to change the contents of const char *ptr?的更多相关文章
- Redis中的数据结构
1. 底层数据结构, 与Redis Value Type之间的关系 对于Redis的使用者来说, Redis作为Key-Value型的内存数据库, 其Value有多种类型. String Hash L ...
- unity导出工程导入到iOS原生工程中详细步骤
一直想抽空整理一下unity原生工程导入iOS原生工程中的详细步骤.做iOS+vuforia+unity开发这么长时间了.从最初的小小白到现在的小白.中间趟过了好多的坑.也有一些的小小收货.做一个喜欢 ...
- Array类
class Array Arrays are ordered, integer-indexed collections of any object. Array indexing starts at ...
- 转:RTMPDump源代码分析
0: 主要函数调用分析 rtmpdump 是一个用来处理 RTMP 流媒体的开源工具包,支持 rtmp://, rtmpt://, rtmpe://, rtmpte://, and rtmps://. ...
- 基于Httpfs访问HDFS的C++实现
Httpfs是hadoop2.x中hdfs项目的内置应用,基于tomcat和jesery,对外提供完备HDFS操作的RESTful接口,无需安装客户端,可方便实现数据交互,如从windows访问存储在 ...
- libcurl的封装,支持同步异步请求,支持多线程下载,支持https
最近在做一个项目,需要用到http get post等 需求分析需要做到同步和异步,异步请求的返回以可选的回调通知的方式进行. 本人以Linux为例,一步一步的来实现. 配置并且编译libcurl我以 ...
- leveldb 学习记录(四)Log文件
前文记录 leveldb 学习记录(一) skiplistleveldb 学习记录(二) Sliceleveldb 学习记录(三) MemTable 与 Immutable Memtablelevel ...
- 5、QT分析之网络编程
原文地址:http://blog.163.com/net_worm/blog/static/127702419201002842553382/ 首先对Windows下的网络编程总结一下: 如果是服务器 ...
- 安卓加固之so文件加固
一.前言 最近在学习安卓加固方面的知识,看到了jiangwei212的博客,其中有对so文件加固的两篇文章通过节加密函数和通过hash段找到函数地址直接加密函数,感觉写的特别好,然后自己动手实践探索s ...
随机推荐
- C#时间格式 tostring、toshortdatestring、toshorttimestring
在c#语言中的时间处理有几种方式: 首先获取当前时间:var date=new DateTime.Now; date.ToString()----2111-1-20 11:44:47 date.ToS ...
- Webservice发布出现 测试窗体只能用于来自本地计算机的请求
今天发布了一个接口,一开始以为是.netframework版本的问题,从3.5降到2.0到服务器发布,发布后还是会出现 测试窗体只能用于来自本地计算机的请求 上网查找资料发现原来是 webconfig ...
- (转)如何构建高性能,稳定SOA应用之-负载均衡-Decoupled Invocation(一)
当我们在为一个软件设计架构的时候,我们不仅仅要确保所做出来的架构要满足系统的业务需求,更加要确保做出来的架构要满足可维护性,安全,稳定性的非业务行的需求. 另外一个非常重要的非功能性需求就是性能.性能 ...
- c/c++面试总结(2)
4.深拷贝和浅拷贝 (1)什么时候会用到拷贝函数 一个对象以值传递的方式传入函数(就是作为入参) 一个对象以值传递的方式从函数返回(就是作为返回值) 一个对象需要通过另外一个对象进行初始化 (2)是否 ...
- UIKit,Core Data , Core Graphics, Core Animation,和OpenGLES框架
iOS的主要框架介绍 框架是一个目录,这个目录包含了共享库,访问共享库里代码的头文件,和其它的图片和声音的资源文件.一个共享库定义的方法或函数可以被应用程序调用. IOS提供了很多你可以在应用程序 ...
- 启动 mysql 失败 Warning:The /usr/local/mysql/data directory is not owned by the 'mysql' or '_mysql'
Warning:The /usr/local/mysql/data directory is not owned by the 'mysql' or '_mysql' 这应该是某种情况下导致/usr/ ...
- 解决Win7下运行php Composer出现SSL报错的问题
以前都在linux环境使用php composer.今天尝试在win7下运行composer却出现SSL报错: D:\data\www\mmoyu\symapp>php -f %phprc%\c ...
- 让ImageView可以使用gif的方法
在自己的包中添加MyGifView.java(直接复制,粘贴),读取gif资源在MyGifView中第20行读取: MyGifView.java: package com.zzw.testgifuse ...
- Color About——Second
下面来简要的说一下Android开发中如何对某一个Activity进行背景色的设置.下面我以名字为FirstActivity的Activity的背景色的设置进行说明,先说一下Drawable类: 关于 ...
- 重绘panel控件,实现panel的阴影效果
最近想在项目中添加一个要有阴影的panel控件,找了好多资料,最后通过采用图片的方式实现了panel的阴影效果,效果图如下: 重绘代码如下: using System; using System.Co ...