为什么程序 return 在我输入指向字符串文字的指针时出现段错误,但在我输入指向数组的指针时却没有?
Why does program return a seg fault when I input a pointer to a string literal but not when i input a pointer to an array?
当我将 char * 字面值传递给 trim() 时,它会出现段错误,但是当我发送一个数组指针时,它会起作用,为什么这不起作用?
int main(void){
/* If instead I have a char s[100] = "Hi ";
* it works as intended so why does it not work when i pass this.*/
char *s = "Hi ";
printf("<%s>\n", s);
trim(s);
printf("<%s>\n", s);
}
/* Trims all white-space off at end of string. */
void trim(char *s){
while (*s != '[=11=]') ++s;
--s;
while (*s == ' ') --s;
*(++s) = '[=11=]';
}
修改字符串文字的内容在 C 中是未定义的行为,这意味着它可能导致任何类型的错误行为,包括崩溃。从概念上讲,字符串文字是 cost char *
,但由于历史原因,它的类型是非常量。这意味着将字符串文字分配给 char *
变量编译没有错误,但实际编写的程序不是有效的 C 程序。
崩溃的直接原因是编译器选择将字符串文字放在只读内存中。这样的内存由 OS 保护,试图修改它的程序会自动终止。
当我将 char * 字面值传递给 trim() 时,它会出现段错误,但是当我发送一个数组指针时,它会起作用,为什么这不起作用?
int main(void){
/* If instead I have a char s[100] = "Hi ";
* it works as intended so why does it not work when i pass this.*/
char *s = "Hi ";
printf("<%s>\n", s);
trim(s);
printf("<%s>\n", s);
}
/* Trims all white-space off at end of string. */
void trim(char *s){
while (*s != '[=11=]') ++s;
--s;
while (*s == ' ') --s;
*(++s) = '[=11=]';
}
修改字符串文字的内容在 C 中是未定义的行为,这意味着它可能导致任何类型的错误行为,包括崩溃。从概念上讲,字符串文字是 cost char *
,但由于历史原因,它的类型是非常量。这意味着将字符串文字分配给 char *
变量编译没有错误,但实际编写的程序不是有效的 C 程序。
崩溃的直接原因是编译器选择将字符串文字放在只读内存中。这样的内存由 OS 保护,试图修改它的程序会自动终止。