首页 > 解决方案 > 尝试打印 %s 时出现分段错误(核心转储)

问题描述

我正在学习https://www.root-me.org/fr/Documentation/Appplicatif/Chaine-de-format-lecture-en-memoire的课程

这是我的代码:

char comment[200];
printf("Test string");
scanf("%s",comment);
printf(comment);

当我输入注释时,即“%s”,它给出了一个分段错误。

根据课程,它应该打印“测试字符串”。

我的代码有什么问题?

标签: c

解决方案


如果我理解正确,您在标准输入中写入“%s”。

 comment is "%s"
 printf(comment) is printf("%s")

这将导致 99% 的时间出现段错误。因为您在 printf 参数中使用的 %s 没有有效的 C 字符串。

与应该工作的这个版本进行比较:而不是 printf(comment),使用 printf(comment, "some text")

 comment is "%s"
 printf(comment, "some text") is printf("%s", "some text")

您正在传递一个带有无法正确解释的转换标志的字符串。您的输入不安全。


推荐阅读