c - printf 在 strcpy 中出现段错误后执行?

标签 c printf strcpy

我有以下代码:

  char buf[10];
  strcpy(buf, "This is a string longer than way longer than ten characters.");
  printf("%s\n", buf);  

我知道第二行会导致段错误,因为我写入的内容超出了数组 buf 的长度,因为我得到以下结果:

  ./a.out
  This is a string longer than way longer than ten characters.
  Segmentation fault (core dumped)

为什么执行 printf 命令时 strcpy 会出现段错误?我在没有 print 语句的情况下运行,只得到一个段错误。

最佳答案

用 C 语言编码,您可以跟踪数组的大小。您将使用不专用于变量的内存。您可以毫无问题地使用它,但请记住,这个“空闲”内存可以分配给您之后可能使用/声明的任何变量!这就是为什么字符串中唯一“ protected ”的部分是前 10 个字符,因为您声明了它

关于c - printf 在 strcpy 中出现段错误后执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49552058/

相关文章:

c++ - 用 strncpy 替换 strcpy

c - OpenGL 中的纹理映射(使用 SOIL)

c - 交换两个相邻节点的单向链表

c - 如何在 C 中使用逗号作为千位分隔符来格式化数字?

java - System.out.printf 与 System.out.format

c - 带有结构体指针数组的 strcpy() 的段错误

c - 尝试打印 double 时程序崩溃(但其他类型都可以)

c - c中的结构体链表

c - printf 语句中的额外输出行

c - strcpy 段错误