我无法理解为什么c中出现了分段错误错误

web*_*oon 2 c segmentation-fault

我写了一些C程序,如下所示.

 #include <stdio.h>
 #include <string.h>

 main() {
   char *s1 = "hello world!" ;
   char *sto = "it's original string" ;
   //copy
   strcpy( sto, s1 ) ;  

   printf( "%s", sto ) ;

 }
Run Code Online (Sandbox Code Playgroud)

是的,处理这个问题的文章太多了.我读了每篇文章.所以我发现没有初始化的变量导致错误.

但是,我认为这段代码没有错误,因为sto变量已经初始化为"它是~~ bla bla"的值.

我是关于c的新手,请善待我.谢谢.

Nat*_*man 5

both s1sto指向常量字符串的指针.

您试图sto用不同的字符串覆盖指向的字符串,但这是一个常量,因此您尝试编写只读区域时会遇到段错误.


Lin*_*cer 5

在C中,您必须管理存储字符串的存储器.

字符串文字,诸如"This is a string"被存储在只读存储器中.

您无法更改其内容.

但是,你可以这样写:

main()
{
  char *s1 = "hello world!" ;

  // This will allocate 100 bytes on the stack. You can use it up until the function returns.
  char sto[100] = "it's original string" ;
  //copy
  strcpy( sto, s1 ) ;  

  printf( "%s", sto ) ;
}
Run Code Online (Sandbox Code Playgroud)