Hi, I have encountered a strange problem of double free corruption. Through debugging, I find the problem is at the end of the entropy function, but I cannot figure out why. Thanks for the help.
Code:
#include<iostream>
#include<iomanip>
#include<string.h>
#include<fstream>
#include<sstream>
#include<vector>
#include<string>
#include<math.h>
#include<stdlib.h>
#include<map>
using namespace std;
int p1_to_num_MJ(string aa){
map <string,int> AAcode;
AAcode["A"] = 8;
AAcode["C"] = 0;
AAcode["D"] = 14;
AAcode["E"] = 15;
AAcode["F"] = 2;
AAcode["G"] = 9;
AAcode["H"] = 16;
AAcode["I"] = 3;
AAcode["K"] = 18;
AAcode["L"] = 4;
AAcode["M"] = 1;
AAcode["N"] = 12;
AAcode["P"] = 19;
AAcode["Q"] = 13;
AAcode["R"] = 17;
AAcode["S"] = 11;
AAcode["T"] = 10;
AAcode["V"] = 5;
AAcode["W"] = 6;
AAcode["Y"] = 7;
AAcode["X"] = -1;//STOP
//check for valid amino acid
map <string, int> :: const_iterator Iter;
Iter = AAcode.find(aa);
if ( Iter == AAcode.end( ) ){
cerr << "Invalid amino acid: "<< aa << endl;
exit(1);
}
return AAcode[aa]; //returns 0 if aa code is invalid
}
double entropy(const vector<string> &seq)
{
int n = seq.size();
int k = seq[0].length();
vector<double> et(k,0);
int i;
for(i=0;i<k;i++)
{
vector<double> p(20,0);
int j;
for(j=0;j<n;j++)
{
p[p1_to_num_MJ(seq[j].substr(i,1))]++;
}
//cout << "bp0" << endl;
for(j=0;j<20;j++)
{
//cout << j << "\t" << p[j] << endl;
p[j] = p[j]/n;
if(p[j] == 0 || p[j] == 1)
{
}
else
{
et[i] += (-(p[j]*log(p[j])));
}
}
/////////***********************DEAD HERE********************////
}
//cout << "bp0.5" << endl;
double sum=0;
//cout << "bp1" << endl;
for(i=0;i<k;i++)
{
sum += et[i];
}
//cout << "bp1.5" << endl;
sum /= k;
//cout << "bp2" << endl;
return sum;
}
int main()
{
int node = 1;
int pop = 1000;
int start = 1851;
int end = 3951;
string ofile;
ostringstream ofile_os(ofile);
ofile_os << "seq_entropy_" << node << "_" << pop << "_" << start << "_" << end << ".txt";
ofile = ofile_os.str();
ofstream out(ofile.c_str());
int i;
for(i=start;i<=end;i+=50)
{
cout << "current generation: " << i << endl;
vector< vector<string> > seq;
seq.resize(10);
int j;
string file;
ostringstream file_os(file);
file_os << "RUN1.gen" << setw(10) << setfill('0') << i << ".snap_sex." << setw(3) << setfill('0') << node << ".a";
file = file_os.str();
ifstream in(file.c_str());
if(in.is_open())
{
string line;
while(getline(in,line))
{
//cout << line << endl;
istringstream instr(line);
string field_1;
instr >> field_1;
if(field_1 == "G")
{
int f2,f6,f7;
double f3, f4, f5;
string nseq;
instr >> f2 >> f3 >> f4 >> f5 >> f6 >> f7 >> nseq;
seq[f2].push_back(nseq);
}
}
in.close();
}
else
{
cerr << "file not exist: " << file << endl;
exit(1);
}
out << i << "\t";
//cout << "bp1" << endl;
for(j=0;j<10;j++)
{
cout << "seq_num: " << j << endl;
out << entropy(seq[j]) << "\t";
}
out << endl;
}
out.close();
return 0;
}