I will try to explain the issue as best as I can. First I will present the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
for (int i=0; i<200000; i++){
//3 variables dealing with pathways
vector<int> MCpathPops;
vector<vector<int> > MCpaths;
vector<int> pathway=getPathway();
//3 variables dealing with ionisation times
int count=0;
vector<vector<vector<double> > > MCionTimes;
vector<double> ionTimes = getIonTimes(); //Gets ionisation times, passed by reference
vector<vector<int> >::iterator iter=find(MCpaths.begin(), MCpaths.end(), pathway);
//Looks in MCpaths, if pathway is in MCpaths, an iterator is returned pointing to the first element of the pathway.
//If pathway is not in MCpaths it returns an iterator to the end of MCpaths.
if(iter != MCpaths.end()) { //If pahtway is in MCpahts
MCpathPops[distance(MCpaths.begin(), iter)]+=1;
MCionTimes[distance(MCpaths.begin(), iter)].push_back(ionTimes);
}
else{ //If pathway is not in MCpaths
MCpaths.push_back(pathway);
MCpathPops.push_back(1);
vector<vector<double> > empty; //TODO: Change
MCionTimes.push_back(empty);
MCionTimes[count].push_back(ionTimes);
count ++;
}
ionTimes.clear();
}
|
The question is the following:
There are somewhere between 10-20 pathways which are stored in the MCpaths. The MCpathsPops, keeps track of how many times each pathway appeared (a few thousand times each).
Now I want to store the ionisation times of each pathway (200,000 in total) in MCionTimes. However, this leads to a memory leak and the program crashing at around 20,000 repetitions. I don't understand why that is. Why is it that when I push_back() the ionTimes variable, it causes a memory leak?
Note, the ionTimes variable, might be either size 0,1,2,3 or 4.
eg1. ionTimes= []
eg2. ionTimes=[0.5]
eg3. ionTimes=[-2.1,3.7] and so on
Note2, I have also tested the code using the following change in the if loop:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
...
...
if(iter != MCpaths.end()) { //if pathway in MCpaths
MCpathPops[distance(MCpaths.begin(), iter)]+=1;
vector<double> en;
en.push_back(1);
en.push_back(1);
en.push_back(1);
en.push_back(1);
MCionTimes[distance(MCpaths.begin(), iter)].push_back(en);
}
...
...
|
where every time I pass a vector with 4 entries in the MCionTimes and I don't encounter the memory leak. It only appears when I am pushing back a vector acquired from the function getIonTimes().
Note3, I also tried passing the ionTimes by value from the getIonTimes() function. The result is still the same
The error I get is the following:
Segmentation fault (core dumped)
Any ideas on how to fix this issue? Please help!