Segmentation fault (core dumped)含义及我的C程序报错原因咨询
Segmentation fault (core dumped) 原因分析及修复
什么是Segmentation fault (core dumped)?
这是Unix/Linux系统下的常见程序错误:当程序试图访问不属于它的内存区域(比如未授权地址、只读内存、已释放的内存)时,操作系统会直接终止程序,并生成core dump文件(包含程序崩溃时的内存快照),用于后续调试。
你的代码问题所在
错误根源在最后三个printf语句——你用单引号包裹了字符串,但C语言中,单引号仅用于表示单个字符(如'a'),多字符字符串必须用双引号(如"hello")。
printf('roses are %s\n', color); // 错误:单引号包裹多字符内容 printf('%s are blue\n', Noun); // 错误:同上 printf('I love %s\n', celebrity); // 错误:同上
在C中,'roses are %s\n'会被当作多字符常量,它的实际值是编译器定义的整数,而printf的第一个参数需要的是字符串指针(const char*)。把这个整数当作内存地址传递给printf时,程序会试图访问非法地址,直接触发Segmentation fault。
修复后的代码
将所有单引号替换成双引号即可:
#include <stdio.h> #include <stdlib.h> int main() { char color[20]; char Noun[20]; char celebrity[20]; printf("Enter the color"); scanf("%s", color); printf("enter the Noun"); scanf("%s", Noun); printf("enter the celebrity"); scanf("%s", celebrity); printf("roses are %s\n", color); printf("%s are blue\n", Noun); printf("I love %s\n", celebrity); return 0; }
额外提示
使用scanf("%s")读取输入时,要注意输入内容不能超过数组长度(比如这里的20字节),否则会导致缓冲区溢出,同样可能引发Segmentation fault或其他未知错误。如果需要读取带空格的字符串,可以改用fgets。
内容的提问来源于stack exchange,提问作者Monisha Sellamuthu
相关产品推荐
相关产品推荐

