问题描述
尝试修改字符串文字会导致未定义的行为:
Attempting to modify a string literal causes undefined behavior:
char * p = "wikipedia";
p[0] = 'W'; // undefined behaviour
防止这种情况的一种方法是将其定义为数组而不是指针:
One way to prevent this is defining it as an array instead of a pointer:
char p[] = "wikipedia";
p[0] = 'W'; // ok
为什么 char*
会导致未定义的行为,而 char[]
不会?
Why does char*
cause undefined behaviour, while char[]
doesn't?
推荐答案
任何修改 C 字符串文字的尝试都有未定义的行为.编译器可能会安排将字符串文字存储在只读内存中(受操作系统保护,而不是字面意义上的 ROM,除非您在嵌入式系统上).但是语言不需要这个;作为一名程序员,这取决于您是否正确.
Any attempt to modify a C string literal has undefined behaviour. A compiler may arrange for string literals to be stored in read-only memory (protected by the OS, not literally ROM unless you're on an embedded system). But the language doesn't require this; it's up to you as a programmer to get it right.
一个足够聪明的编译器可能会警告您,您应该将指针声明为:
A sufficiently clever compiler could have warned you that you should have declared the pointer as:
const char * p = "wikimedia";
虽然没有 const
的声明在 C 中是合法的(为了不破坏旧代码).但是不管有没有编译器警告,const
都是一个非常好的主意.
though the declaration without the const
is legal in C (for the sake of not breaking old code). But with or without a compiler warning, the const
is a very good idea.
(在 C++ 中,规则不同;C++ 字符串文字,与 C 字符串文字不同,实际上是 const
.)
(In C++, the rules are different; C++ string literals, unlike C string literals, really are const
.)
当您使用文字初始化数组时,文字本身仍然存在于程序映像的潜在只读区域中,但它被复制到本地数组中:
When you initialize an array with a literal, the literal itself still exists in a potentially read-only region of your program image, but it is copied into the local array:
char s[] = "wikimedia"; /* initializes the array with the bytes from the string */
char t[] = { 'w', 'i', ... 'a', 0 }; /* same thing */
这篇关于为什么 char* 会导致未定义的行为,而 char[] 不会?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!