这段c++代码总是出现segmentation fault,希望大家指出错误

这段c++代码总是出现segmentationfault,希望大家指出错误#include<iostream>#include<vector>#include<ctime... 这段c++代码总是出现segmentation fault,希望大家指出错误#include<iostream>
#include<vector>
#include<ctime>
#include<cstdlib>
using namespace std;
class virus
{
public:
double reproductionrate;
double reproduce;
double resistance;
virus()
{
resistance=rand()/(RAND_MAX+1.0);
reproductionrate=0.2;
}
void Reproduce()
{
reproduce=rand()/(RAND_MAX+1.0);
}
};
class patient
{
public:
double immunity;
int numVirusCell;
virus* vnow[3000];
vector<virus*> v;
patient(double i,int n)
{
immunity=i;
numVirusCell=n;
}
void takedrug()
{
immunity+=0.1;
}
void see()
{
virus* p[3000];
int i,j,add=0;
for(i=0;i<numVirusCell;i++)
{
p[i]=new virus;
}
for(i=1;i<=100;i++)
{
for(j=0;j<numVirusCell;j++)
{
p[j]->Reproduce();
if(p[j]->resistance<=immunity)
{
numVirusCell--;
v.push_back(p[j]);
delete p[j];
p[j]=NULL;
}
else{
if(p[j]->reproduce>immunity&&p[j]->reproduce>p[j]->reproductionrate)
{
numVirusCell++;
vnow[j+add]=p[j];
vnow[j+add+1]=new virus;
v.push_back(vnow[j+add+1]);
add++;
}
else
{
vnow[j+add]=p[j];
}
}
}
add=0;
if(numVirusCell>1000)cout<<"第"<<i<<"小时,达到1000"<<endl;
else
for(j=0;j<numVirusCell;j++)p[j]=vnow[j];
}
}
};
int main()
{
srand(time(NULL));
patient p1(0.1,10);
cout<<p1.immunity<<endl;
p1.see();
return 0;
}
展开
 我来答
wenqing8585
2018-04-11 · TA获得超过8258个赞
知道大有可为答主
回答量:8078
采纳率:70%
帮助的人:3977万
展开全部
numVirusCell++; 之后你没有给p[numVirusCell-1]赋值,导致再次执行
for (j = 0; j<numVirusCell; j++)
{
p[j]->Reproduce(); ----》这里会访问p[10]所指向的对象,而p[10]并未初始化,所以会发生非法访问,造成程序崩溃
更多追问追答
追问
我new一个对象的空间赋给该类指针后,这个对象空间会自己调用构造函数吗
追答
wodeshijielly
2018-04-11
知道答主
回答量:8
采纳率:25%
帮助的人:6904
展开全部
错误代码
#include "string.h"#include <stdlib.h>#include <stdio.h>void func1(char ** dest,char * src,int n) {
(*dest) = (char*)malloc(sizeof(char)*n); strcpy(*dest,src);

}int main(int argc,char** args) { char ** p = NULL; char str[] = "foreach_break"; int len = sizeof(str); printf("%d\n",len);
func1(p,str,len);
printf("%s\n",*p); free(p);
p = NULL;
}1234567891011121314151617181920

正确代码
#include "stdio.h"#include "string.h"#include "stdlib.h"void func1(char ** dest,char * src,int n) {
(*dest) = (char*)malloc(sizeof(char)*n); strcpy(*dest,src);

}int main(int argc,char** args) { char * p = NULL; char str[] = "foreach_break"; int len = sizeof(str); printf("%d\n",len);
func1(&p,str,len); printf("%s\n",p); free(p); //p = NULL;}12345678910111213141516171819202
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式