绛鹤晨严 2014-07-04 09:51 采纳率: 0%
浏览 3375

很奇怪的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)

  • 写回答

2条回答

  • seanxq 2014-09-24 10:11
    关注

    你需要给temp分配内存,有或没有那行代码,你的程序都可能crash.

    最简单的办法:

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

    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料