开发者社区> 问答> 正文

egmentation fault(core dumped)的问题

#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)

展开
收起
a123456678 2016-03-04 18:26:25 3921 0
1 条回答
写回答
取消 提交回答
  • 你需要给temp分配内存,有或没有那行代码,你的程序都可能crash.

    最简单的办法:

    char *temp ==》 char temp[1025];

    2019-07-17 18:52:43
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
KR^X- Comprehensive- Kernel-Protection-Against-Just-In-Time-Code-Reuse 立即下载
Architecting a Multi-Tenanted Platform 立即下载
How to Build a Successful Data 立即下载