"C + + programming Art" on the second chapter of the code to run the first Test program error, the Internet to find the next, did not find a concrete solution, CSDN on the Netizen said is in the collect inside out of the wrong.
All right, I'll do it myself redeployment to change it.
#include <iostream>#include<New>#include"gc.h" using namespacestd;intMain () {gcptr<int>p; Try{p=New int; } Catch(Bad_alloc exc) {cout<<"Allocation failure!\n"; return 1; } *p = the; cout<<"Value at p is:"<< *p <<Endl; intK = *p; cout<<"k is"<< k <<Endl; System ("Pause"); return 0; }
In this function, one-step debugging, found that the last return of 0 that caused the interruption, it seems really is the Collect function error.
1Template <classTintSize>2 BOOLGcptr<t, size>:: Collect () {3 BOOLMemfreed =false;//whether there is memory being freed by the token4 5 #ifdef DISPLAY6cout <<"before garbage collection for"; 7 showlist (); 8 #endif 9 Tenlist<gcinfo<t> >:: iterator P; One //There's a two-tiered loop, and every time we release the memory, we're going to search the gclist from scratch. A Do { - - //Scan Gclist to find out if there is an entry for RefCount 0 when this entry is found the //call the Remove function to remove it, and remove is a member of the STL list class - for(P = gclist.begin (); P! = Gclist.end (); p++) { - if(P->refcount >0) - Continue; + -Memfreed =true; + A at - //frees null-pointing memory address - if(p->memptr) { - if(p->IsArray) { - #ifdef DISPLAY -cout <<"Deleting array of size" in<< p->arraysize <<Endl; - #endif to Delete[] p->memptr;//releasing an array + } - Else { the #ifdef DISPLAY *cout <<"Deleting:" $<< * (T *) p->memptr <<"\ n"; Panax Notoginseng #endif - Deletep->memptr;//releasing an object the } + A } the //removes an empty-pointing entry from gclist. +Gclist.remove (*p); - $ //re-search $ Break; - } - the} while(P! =gclist.end ()); - Wuyi #ifdef DISPLAY thecout <<"After garbage collection for"; - showlist (); Wu #endif - About returnMemfreed; $}
Note: The above is a modified code
The Collect function was found to perform gclist.remove (*p); After this step, the back of the P->refcount,p->isarray and other information is all wrong, suddenly wake up,
Because this step frees the P node and later reads the information about the P node, it causes an error to occur. The correct approach is to first read the P-node RefCount,
IsArray, and then releases the Memptr pointer in P, and finally releases the P node. The modified code is as shown above.
"C + + Programming Art" chapter II of the garbage collector source Bug modification