开发者社区> 问答> 正文

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怎么办?

展开
收起
a123456678 2016-03-09 11:13:14 2990 0
1 条回答
写回答
取消 提交回答
  • if (temp = NULL) 这句写错了, 应该是if (temp == NULL) 你那样写if判断永远为真
    改了之后的截图如下:
    screenshot

    2019-07-17 18:55:38
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Easy,scalable,Fault-tolerant S 立即下载
Towards A Fault-Tolerant Speaker Verification System: A Regularization Approach To Reduce The Condition Number 立即下载
Fault Tolerance in Spark 立即下载