绛鹤晨严 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];

    评论

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题