在此声明中:
char *a = "string1"
字符串字面是什么?是string1
吗?因为这个帖子What is the type of string literals in C and C++?说的不同。
据我所知
int main()
{
char *a = "string1"; //is a string- literals allocated memory in read-only section.
char b[] = "string2"; //is a array char where memory will be allocated in stack.
a[0] = 'X'; //Not allowed. It is an undefined Behaviour. For me, it Seg Faults.
b[0] = 'Y'; //Valid.
return 0;
}
请添加除上述要点以外的一些细节。感谢。
调试输出显示错误 a[0] = 'Y';
Reading symbols from /home/jay/Desktop/MI/chararr/a.out...done.
(gdb) b main
Breakpoint 1 at 0x40056c: file ddd.c, line 4.
(gdb) r
Starting program: /home/jay/Desktop/MI/chararr/a.out
Breakpoint 1, main () at ddd.c:4
4 {
(gdb) n
6 char *a = "string1";
(gdb) n
7 char b[] = "string2";
(gdb)
9 a[0] = 'Y';
(gdb)
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400595 in main () at ddd.c:9
答案 0 :(得分:14)
您可以将字符串文字视为“由双引号括起来的字符序列”。 此字符串存储在只读内存,尝试修改此内存会导致未定义的行为。
那你怎么得到分段错误?
- 重点是char *ptr = "string literal"
使ptr
指向存储字符串文字的只读内存。因此,当您尝试访问此内存时:ptr[0] = 'X'
(相当于*(ptr + 0) = 'X'
),这是内存访问冲突。
另一方面:char b[] = "string2";
分配内存并将字符串"string2"
复制到其中,因此修改它是有效的。当b
超出范围时,将释放此内存。