开发者社区> 问答> 正文

很奇怪的segmentation fault(core dumped)的问题。c++

源代码如下,统计文件中字符串出现个数

#include
 #include
 #include
 #include
 using namespace std;
 int Num;
 int main(int argc,char *argv[]){ //参数分别是字符串和文件
int length=strlen(argv[1]); //字符串长度
ifstream ifile;
 ifile.open(argv[2],ios::binary);
 ifile.seekg(0,ios::beg);
 char *temp, *ptr,*p; //temp一行行读入文件内容,*ptr *索引指针
while(1){
 if(ifile.tellg()==EOF)break; //判断文件是否结束
//cout<<ifile.tellg()<<endl; 
 ifile.getline(temp,1024);
 ptr=temp;
           (注意!!!!!) //cout<<temp<<strlen(temp)<<endl;
//cout<<Num<<endl;
 while(1){
  if(p=strstr(ptr,argv[1])){
   Num++;
//cout<<p<<endl;
   ptr=p+length;
  }else break;
} 
 memset(temp,0,1024);
}
cout<<Num<<endl;
}

测试文件text.txt/dat(其中有空格论坛不能显示,所以第一次运行统计数字和看起来不一样)

helloworldhelloworld
 helloworld

 world

 world

 helloworld 

运行./a.out world text.txt
两次运行结果

 第一次("注意"那行没有被注释时结果)
helloworldhelloworld20
 helloworld12
 world 7
 world 8
 helloworld10//temp&strlen(temp)
 0//最后一次读入空,长度为0
 6//Num

第二次注释那一行,重新编译运行,显示错误
`
segmentation fault(core dumped)
`
按理那一行没什么作用,只是看读入是否正确用的,为什么会对结果产生影响???
环境是fedora
另,如果换成windows 不报错,但结果恒为0
ubuntu即使有那一行也报错,错误一样segmentation fault(core dumped)

展开
收起
杨冬芳 2016-07-08 16:28:56 4879 0
1 条回答
写回答
取消 提交回答
  • IT从业

    你需要给temp分配内存,有或没有那行代码,你的程序都可能crash.最简单的办法:char *temp ==》 char temp[1025];temp空间不够,只是一个指针char temp[2048];

    2019-07-17 19:53:38
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
使用C++11开发PHP7扩展 立即下载
GPON Class C++ SFP O;T Transce 立即下载
GPON Class C++ SFP OLT Transce 立即下载