C ++ memory leaks posture of --eof () and delete releases memory

First thing to say, with codeblocks students please pay close attention to the change uninstall Visual Studio, a good IDE can make you more with less! !

Let me eof (), lesson is this stuff he did not return after the last line read null value, he will continue to read later, because the end of file is the last character of the next character (is not it a bit like a character ? string), see this blog: https://blog.csdn.net/rebel_321/article/details/4927464

Paste the code:

1 void Graph::InputListGene(bool TOG,int nbNodes,ifstream& f){
2     string* line = new string[nbNodes];
3     int count =0;
4     while(!f.eof()){
5         if(count >=nbNodes) break;//the eof character is the one after the last character
6         getline(f,line[count],';');
7        cout<<line[count]<<endl;
8         count++;
9     }

If you do not if judged on line 5, line 6 to the last cycle will be out of bounds array access.

Also on the delete, this thing right, we must remember that it is called "free the memory," I understand to cancel the pointer points to the location of its current relevance. So, after not delete a null pointer, the pointer does not become null themselves, it must be assigned null after the delete.

Paste the code:

 1 int id=p;
 2             if(!TOG){//undirected
 3                 for (auto iter = listEdges.begin(); iter != listEdges.end(); iter++) {//to detect if the new edge is redundant
 4                     if ((*iter)->destination == e->source && (*iter)->source == e->destination) { //redundance detected
 5                         id = (*iter)->getID();//the id of an edge should be unique
 6                         //cout << "e id before del:" << e->id << endl;
 7                         p--;
 8                         delete e;
 9                         //cout << "e id :" << e->id << endl;
10                         e = NULL;
11                         break;
12                     }
13                     else
14                         id = p;
15                 }
16             }
17             if (e) {//if the new edge is not redundant 
18                 cout << "true,id is " <<e->id<< endl;
19                 cout << "Edge_Id:" << e->id << " src:" << e->source->id << " dest:" << e->destination->id << " weight:" << e->cost << endl;
20                 listEdges.push_back(e);
21             }
22             listVertex[i]->nextEdgeNode.push_back(make_pair(dest,id));
23             p++;
24             delete[] cstr;
25         }

Main line 4 by the if rule out without adding to listEdge inside Edge object, where the absence of line 10 then line 19 will be given, because e has a non-null pointer, 17 line did not achieve the original determination null , this is equivalent to no if.

Guess you like

Origin www.cnblogs.com/mrlonely2018/p/11906900.html