if (temp = NULL) 这句写错了, 应该是**if (temp == NULL)** 你那样写if判断永远为真
改了之后的截图如下:
Segmentation fault问题
//c语言实现输入任意长度的字符串
#include
#include
int main (void )
{
char *string = NULL ,*temp = NULL;
char ch;
int i;
//先将字符串初始化为空
string = (char *)malloc(1);
string[0] = '\0';
//len为实际长度(包括空字符)
int len = 1;
while ((ch = getchar())!= '\n')
{
//申请一个新字符串
temp = (char *)malloc(len+1);
if (temp = NULL)
{
printf("内存不足!");
free(string);
exit(0);
}
i=0;
while (string[i] != '\0'&&i<len)
{
//把原字符串复制到新字符串
temp[i] = string[i];
i++;
}
//把新字符归位
temp[i] = ch;
//把空字符归位
temp[i+1] = '\0';
//释放源字符,这一步很关键,否
//则会造成内存泄露
free(string);
string = temp;
len++;
}
int j=0;
while (string[j]!='\0')
{
putchar(string[j]);
j++;
}
return 0;
}
运行时显示Segmentation fault怎么办?
- 点赞
- 写回答
- 关注问题
- 收藏
- 复制链接分享
- 邀请回答
1条回答
为你推荐
- 做顺序表的删除操作时出现Segmentation fault
- c语言
- 1个回答
- received signal SIGSEGV, Segmentation fault
- 是什么导致Go中出现此段错误?
- pointers
- segmentation-fault
- 1个回答
- PHPUnit分段错误
- php
- segmentation-fault
- 13个回答
- linux系统运行java相关的程序时出现segmentation fault错误
- 为什么用scanf控制给数值的赋值个数会造成 存访问错误造成Segmentation fault (SIGSEGV)???
- c语言
- 2个回答
- c语言构建单向链表,vs正常运行但是gcc会报错runtime error:segmentation fault。
- c语言
- 1个回答
- “[notice] child pid XXXX退出信号分段错误(11)”在apache error.log中
- QT调试时遇到 Signal name : SIGSEGV Signal meaning : Segmentation fault,但是我已经初始化了变量。
- c++
- 1个回答
- centos 安装bin文件报错segmentation fault
- linux
- 0个回答
- Linux 编译安装libc.so.6时出现Segmentation fault (core dumped)错误导致ls等命令不能用怎么办?
- tensorflow
- linux
- 3个回答
- PAT1024提交时出现问题,提示Segmentation Fault。请帮忙解决
- c
- 1个回答
- centos下 Segmentation fault 错误!
- libpcap抓包程序执行时出现Segmentation fault (core dumped)
- libpcap抓包
- 段错误
- 1个回答
- C++ 使用sort()函数 出现segmentation fault
- ios
- 2个回答
- linux 下 segmentation fault (core dumped) 错误出在哪里
- printf
- linux
- 终端
- 4个回答
- Segmentation fault问题
- Segmentation fault是什么意思?哪里错了
- aaa
- 3个回答
- 为什么出现Segmentation fault,求解释并纠错(谢绝新代码)么么哒、
- c
- flag
- 2个回答
- C语言输出数字团,代码为什么出现Segmentation fault,求解释并纠错??
- c
- 数字
- 代码
- segmentation
- 4个回答