c - 尝试打印 %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”,它给出了一个分段错误。
根据课程,它应该打印“测试字符串”。
我的代码有什么问题?
解决方案
如果我理解正确,您在标准输入中写入“%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")
您正在传递一个带有无法正确解释的转换标志的字符串。您的输入不安全。
推荐阅读
- node.js - TypeError:无法读取未定义的“id”属性
- oracle - 如何使用oracle触发器中的计算值更新同一表中的列
- r - 我的 R for 循环只打印最后一个元素
- oop - “聚合”和“组合”关系之间的关系以及“聚合”和“继承”关系之间的关系
- python - 为什么正则表达式中没有 AND 运算符?
- javascript - JQuery Plugin - 突出显示包含某个单词的内容可编辑框
- javascript - React fetch / doPost 没有返回数据
- javascript - IIS 仍然加载旧的 javascript 文件。如何更新或告诉 iis 加载/获取新的 javascript 文件?
- android - 从 AdapterPager 结果中的当前视图中删除最近的项目到异常错误
- android - kotlin flatten 返回多个订单项