(char *)to(const char *)也很危险但允许? [英] (char *) to (const char *) is also dangerous but allowed?
问题描述
C停止从(char **)到(const char **)的转换。 c-faq.com
sec 11.10对这一点有解释。但是,例如,即使从(char *)到(const char *)的转换也会带来与之前转换相同的危险
。为什么后者简单但危险的一个
在C中是允许的?
$ cat f1.c
int main(void)
{
const char c =''a'';
char * p;
const char * cp = p;
cp =& c;
* p =''x''; / * 8行* /
返回0;
}
$ cc -Aa -g f1.c >
$ ./a.out
巴士错误(coredump)
$ gdb -q ./a.out核心
核心是由'a.out''生成的。
程序终止,信号10,总线错误。
警告:共享库没有私有映射;在重新运行
程序之前,在共享库中设置一个
断点是行不通的。
#0 0x29d4 in main( )在f1.c:8
8 * p =''x'';
(gdb)退出
$
C stops the conversion from (char **) to (const char **). c-faq.com
sec 11.10 has explanation on this point. But, for example, even the
conversion from (char *) to (const char *) brings the same dangerous
as in the previous conversion. Why the latter simple but dangerous one
is allowed in C?
$ cat f1.c
int main(void)
{
const char c = ''a'';
char *p;
const char *cp = p;
cp = &c;
*p = ''x''; /*line 8*/
return 0;
}
$ cc -Aa -g f1.c
$ ./a.out
Bus error(coredump)
$ gdb -q ./a.out core
Core was generated by `a.out''.
Program terminated with signal 10, Bus error.
warning: The shared libraries were not privately mapped; setting a
breakpoint in a shared library will not work until you rerun the
program.
#0 0x29d4 in main () at f1.c:8
8 *p = ''x'';
(gdb) quit
$
推荐答案
cat f1.c
int main(void)
{
const char c =''a'';
char * p;
const char * cp = p;
cp =& c;
* p =''x''; / *第8行* /
返回0;
}
cat f1.c
int main(void)
{
const char c = ''a'';
char *p;
const char *cp = p;
cp = &c;
*p = ''x''; /*line 8*/
return 0;
}
cc -Aa -g f1.c
cc -Aa -g f1.c
./ a.out
总线错误(coredump)
./a.out
Bus error(coredump)
这篇关于(char *)to(const char *)也很危险但允许?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!