Question

I am getting this message after running my program on Unix system:

*** glibc detected *** ./anal: double free or corruption (fasttop):

On windows it is working fine. I had already find that it my be caused by destructor because of using insert and =. probably the error is in this line:

ret = trigrams.insert ( pair<string,int>(tempStr,1) );

But my question is how to resolve it? I need to create copy of both map and iterator? I thin it would be waste of memory. Should i overload the operator "=" to create a copy, but how? I am working usually with java so it is quite wired for me.

int main(int argc, char *argv[]){
map<string,int> trigrams;
pair<map<string,int>::iterator,bool> ret;
map<string,int>::iterator it;
char tmp[3];
FILE *fp = fopen ("new.txt" , "r");
fseek(fp, 0L, SEEK_END);
size_t fileSize = ftell(fp);
cout<<fileSize<<"\n";
ifstream is("new.txt");
string tempStr;
char c;
int i=0;
it = trigrams.begin(); 
#pragma omp parallel for default(shared) shared(trigrams, c, it, ret)  private(i)   
for(i=0; i<=fileSize;i++)          
{
    if((i%3)==0&&(i!=0)){
        tempStr = tmp;  
        tempStr = tempStr.substr(0,3);
        ret = trigrams.insert ( pair<string,int>(tempStr,1) );
        if (ret.second==false) {
            trigrams[tempStr] += 1;
        }
    }
    c = is.get();
    if(c != '\n')          
        tmp[i%3]=c;
}
is.close();            
ofstream file;
file.open ("new3.txt");
for (it=trigrams.begin(); it!=trigrams.end(); ++it){
    file <<it->first<<"  "<< it->second<<"\n";


}
file.close();
return 0;
}

And here is simple program which is working:

int main(int argc, char *argv[]){
map<int,string> trigrams;
pair<map<int,string>::iterator,bool> ret;
map<int, string>::iterator it;
it = trigrams.begin(); 
for(int i=0; i<=100;i++)          
{
    ret = trigrams.insert ( pair<int, string>(i, "tempStr") );
    it++;
}
for (it=trigrams.begin(); it!=trigrams.end(); ++it){
    cout <<it->first<<"  "<< it->second<<"\n";


}
return 0;
}
Était-ce utile?

La solution

I guess you have a race condition here - you simultaneously trying to insert values to a map from different threads, and map is not thread-safe in C++. Races can lead to many nasty things, including double free. The worst thing is that program behavior becomes very random and that may be the reason why it works fine on windows.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top