为什么在写入“char *s"时会出现分段错误?用字符串文字初始化,而不是“char s[]"? [英] Why do I get a segmentation fault when writing to a "char *s" initialized with a string literal, but not "char s[]"?

查看:23
本文介绍了为什么在写入“char *s"时会出现分段错误?用字符串文字初始化,而不是“char s[]"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码在第 2 行收到段错误:

The following code receives seg fault on line 2:

char *str = "string";
str[0] = 'z';  // could be also written as *str = 'z'
printf("%s
", str);

虽然这非常有效:

char str[] = "string";
str[0] = 'z';
printf("%s
", str);

经过 MSVC 和 GCC 测试.

Tested with MSVC and GCC.

推荐答案

参见 C FAQ,问题1.32

:这些初始化之间有什么区别?
char a[] = "字符串文字";
char *p = "字符串文字";
如果我尝试为 p[i] 分配一个新值,我的程序会崩溃.

Q: What is the difference between these initializations?
char a[] = "string literal";
char *p = "string literal";
My program crashes if I try to assign a new value to p[i].

A:字符串文字(正式术语对于 C 中的双引号字符串source) 可以用两个咯不同的方式:

A: A string literal (the formal term for a double-quoted string in C source) can be used in two slightly different ways:

  1. 作为char数组的初始化器,在char a[]的声明中,它指定了初始值该数组中的字符(和,如有必要,其大小).
  2. 在其他任何地方,它都会变成一个未命名的静态字符数组,这个未命名的数组可能会被存储在只读存储器中,并且因此不一定是修改的.在表达式上下文中,该数组立即转换为指针,像往常一样(见第 6 节),所以第二个声明初始化 p指向未命名数组的第一个元素.
  1. As the initializer for an array of char, as in the declaration of char a[] , it specifies the initial values of the characters in that array (and, if necessary, its size).
  2. Anywhere else, it turns into an unnamed, static array of characters, and this unnamed array may be stored in read-only memory, and which therefore cannot necessarily be modified. In an expression context, the array is converted at once to a pointer, as usual (see section 6), so the second declaration initializes p to point to the unnamed array's first element.

有些编译器有一个开关控制是否为字符串文字是否可写(用于编译旧的代码),有些可能有选项导致字符串文字正式被视为 const char 数组(对于更好地捕捉错误).

Some compilers have a switch controlling whether string literals are writable or not (for compiling old code), and some may have options to cause string literals to be formally treated as arrays of const char (for better error catching).

这篇关于为什么在写入“char *s"时会出现分段错误?用字符串文字初始化,而不是“char s[]"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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