Ignore:
Timestamp:
Apr 29, 2010, 2:38:29 PM (15 years ago)
Author:
Tillmann Crueger <crueger@…>
Branches:
Action_Thermostats, Add_AtomRandomPerturbation, Add_FitFragmentPartialChargesAction, Add_RotateAroundBondAction, Add_SelectAtomByNameAction, Added_ParseSaveFragmentResults, AddingActions_SaveParseParticleParameters, Adding_Graph_to_ChangeBondActions, Adding_MD_integration_tests, Adding_ParticleName_to_Atom, Adding_StructOpt_integration_tests, AtomFragments, Automaking_mpqc_open, AutomationFragmentation_failures, Candidate_v1.5.4, Candidate_v1.6.0, Candidate_v1.6.1, ChangeBugEmailaddress, ChangingTestPorts, ChemicalSpaceEvaluator, CombiningParticlePotentialParsing, Combining_Subpackages, Debian_Package_split, Debian_package_split_molecuildergui_only, Disabling_MemDebug, Docu_Python_wait, EmpiricalPotential_contain_HomologyGraph, EmpiricalPotential_contain_HomologyGraph_documentation, Enable_parallel_make_install, Enhance_userguide, Enhanced_StructuralOptimization, Enhanced_StructuralOptimization_continued, Example_ManyWaysToTranslateAtom, Exclude_Hydrogens_annealWithBondGraph, FitPartialCharges_GlobalError, Fix_BoundInBox_CenterInBox_MoleculeActions, Fix_ChargeSampling_PBC, Fix_ChronosMutex, Fix_FitPartialCharges, Fix_FitPotential_needs_atomicnumbers, Fix_ForceAnnealing, Fix_IndependentFragmentGrids, Fix_ParseParticles, Fix_ParseParticles_split_forward_backward_Actions, Fix_PopActions, Fix_QtFragmentList_sorted_selection, Fix_Restrictedkeyset_FragmentMolecule, Fix_StatusMsg, Fix_StepWorldTime_single_argument, Fix_Verbose_Codepatterns, Fix_fitting_potentials, Fixes, ForceAnnealing_goodresults, ForceAnnealing_oldresults, ForceAnnealing_tocheck, ForceAnnealing_with_BondGraph, ForceAnnealing_with_BondGraph_continued, ForceAnnealing_with_BondGraph_continued_betteresults, ForceAnnealing_with_BondGraph_contraction-expansion, FragmentAction_writes_AtomFragments, FragmentMolecule_checks_bonddegrees, GeometryObjects, Gui_Fixes, Gui_displays_atomic_force_velocity, ImplicitCharges, IndependentFragmentGrids, IndependentFragmentGrids_IndividualZeroInstances, IndependentFragmentGrids_IntegrationTest, IndependentFragmentGrids_Sole_NN_Calculation, JobMarket_RobustOnKillsSegFaults, JobMarket_StableWorkerPool, JobMarket_unresolvable_hostname_fix, MoreRobust_FragmentAutomation, ODR_violation_mpqc_open, PartialCharges_OrthogonalSummation, PdbParser_setsAtomName, PythonUI_with_named_parameters, QtGui_reactivate_TimeChanged_changes, Recreated_GuiChecks, Rewrite_FitPartialCharges, RotateToPrincipalAxisSystem_UndoRedo, SaturateAtoms_findBestMatching, SaturateAtoms_singleDegree, StoppableMakroAction, Subpackage_CodePatterns, Subpackage_JobMarket, Subpackage_LinearAlgebra, Subpackage_levmar, Subpackage_mpqc_open, Subpackage_vmg, Switchable_LogView, ThirdParty_MPQC_rebuilt_buildsystem, TrajectoryDependenant_MaxOrder, TremoloParser_IncreasedPrecision, TremoloParser_MultipleTimesteps, TremoloParser_setsAtomName, Ubuntu_1604_changes, stable
Children:
1f7864
Parents:
8cbb97
Message:

Improved comments for the memory tracker

File:
1 edited

Legend:

Unmodified
Added
Removed
  • src/Helpers/MemDebug.cpp

    r8cbb97 rd79639  
    1212
    1313namespace Memory {
     14
     15  // This struct is added before each memory chunk
     16  // and contains tracking information. Anything used
     17  // to track memory cannot use any dynamic memory, so
     18  // we have to resort to classic C-idioms here.
     19  // This struct also contains pointers to the next
     20  // an previous chunks to allow fast traversion of
     21  // all allocated memory blocks
    1422  struct entry_t {
     23    // we seperate the tracking info from the rest
     24    // A checksum will be calculated for this part of
     25    // the struct, so the information in here should
     26    // not change during the lifetime of the memory
    1527    struct info_t {
    16       char file[256];
     28      enum {length = 64};
     29      char file[length];
    1730      int line;
    1831      size_t nbytes;
     
    2639  };
    2740
     41  // start and end of the doubly-linked list
    2842  entry_t *begin=0;
    2943  entry_t *end=0;
    3044
     45  // current amount of allocated memory
    3146  size_t state = 0;
     47  // maximum amount of allocated memory
    3248  size_t max = 0;
    33 
     49  // number of allocations that have been done so far
     50  unsigned int allocs = 0;
     51
     52
     53  // this sets the alignment of the returned memory block
     54  // malloc guarantees an alignment at the 8 byte border,
     55  // so we just do the same
    3456  const int alignment = 8;
    3557
     58  // calculates a simple checksum for the info block
     59  // the checksum is used to find memory corruptions
    3660  inline char calcChecksum(entry_t::info_t *info){
    3761    char *buffer = (char*)info;
     
    4367  }
    4468
     69  // gets the next alignet point which is greater than nbytes
     70  // this function is only called a fixed number of times, so
     71  // there is no need to optimize
    4572  inline size_t doAlign(size_t nbytes){
    4673    int nonaligned = nbytes % alignment;
     
    5380  }
    5481
     82  // Output some state information
    5583  void getState(){
    5684    cout << "Maximum allocated Memory: " << max << " bytes" << endl;
    5785    cout << "Currently allocated Memory: " << state <<" bytes" << endl;
    58 
     86    cout << allocs << " allocated chunks total" << endl;
     87
     88    // simple traversal of the chunk list
    5989    for(entry_t *pos=begin;pos;pos=pos->next){
    6090      cout << "\nChunk of " << pos->info.nbytes << " bytes" << " still available" << endl;
     
    6393  }
    6494
     95  // Deletes an entry from the linked list
    6596  void deleteEntry(entry_t *entry){
    6697    if(entry->isIgnored)
    6798      return;
     99
    68100    if(entry->prev){
    69101      entry->prev->next = entry->next;
    70102    }
    71103    else{
     104      // this node was the beginning of the list
    72105      begin = entry->next;
    73106    }
     
    77110    }
    78111    else{
     112      // this node was the end of the list
    79113      end = entry->prev;
    80114    }
     
    84118
    85119  void _ignore(void *ptr){
     120    // just deletes the node from the list, but leaves the info intact
    86121    static const size_t entrySpace = Memory::doAlign(sizeof(Memory::entry_t));
    87122    entry_t *entry = (Memory::entry_t*)((char*)ptr-entrySpace);
     
    92127void *operator new(size_t nbytes,const char* file, int line) throw(std::bad_alloc) {
    93128
     129  // to avoid allocations of 0 bytes if someone screws up
     130  // allocation with 0 byte size are undefined behavior, so we are
     131  // free to handle it this way
    94132  if(!nbytes) {
    95133    nbytes = 1;
    96134  }
    97135
     136  // get the size of the entry, including alignment
    98137  static const size_t entrySpace = Memory::doAlign(sizeof(Memory::entry_t));
    99138
    100139  void *res;
    101140  if(!(res=malloc(entrySpace + nbytes))){
     141    // new must throw, when space is low
    102142    throw std::bad_alloc();
    103143  }
    104144
     145  // we got the space, so update the global info
    105146  Memory::state += nbytes;
    106147  if(Memory::state>Memory::max){
    107148    Memory::max = Memory::state;
    108149  }
    109 
     150  Memory::allocs++;
     151
     152  // build the entry in front of the space
    110153  Memory::entry_t *entry = (Memory::entry_t*) res;
    111154  entry->info.nbytes = nbytes;
    112155  entry->info.isUsed = true;
    113   strncpy(entry->info.file,file,256);
     156  strncpy(entry->info.file,file,Memory::entry_t::info_t::length);
    114157  entry->info.file[255] = '\0';
    115158  entry->info.line=line;
     159  // the space starts behind the info
    116160  entry->info.location = (char*)res + entrySpace;
    117161
    118   entry->next=0;
    119   entry->prev=Memory::end;
     162  // add the entry at the end of the list
     163  entry->next=0;            // the created block is last in the list
     164  entry->prev=Memory::end;  // the created block is last in the list
    120165  if(!Memory::begin){
     166    // the list was empty... start a new one
    121167    Memory::begin=entry;
    122168  }
    123169  else {
     170    // other blocks present... we can add to the last one
    124171    Memory::end->next=entry;
    125172  }
    126173  Memory::end=entry;
    127174
     175  // get the checksum...
    128176  entry->checksum = Memory::calcChecksum(&entry->info);
     177  // this will be set to true, when the block is removed from
     178  // the list for any reason
    129179  entry->isIgnored = false;
    130180
     181  // ok, space is prepared... the user can have it.
     182  // the rest (constructor, deleting when something is thrown etc)
     183  // is handled automatically
    131184  return entry->info.location;
    132185}
    133186
    134187void *operator new(size_t nbytes) throw(std::bad_alloc) {
     188  // Just forward to the other operator, when we do not know from
     189  // where the allocation came
    135190  return operator new(nbytes,"Unknown",0);
    136191}
    137192
    138193void *operator new[] (size_t nbytes,const char* file, int line) throw(std::bad_alloc) {
     194  // The difference between new and new[] is just for compiler bookkeeping.
    139195  return operator new(nbytes,file,line);
    140196}
    141197
    142198void *operator new[] (size_t nbytes) throw(std::bad_alloc) {
     199  // Forward again
    143200  return operator new[] (nbytes,"Unknown",0);
    144201}
    145202
    146203void operator delete(void *ptr) throw() {
     204  // get the size for the entry, including alignment
    147205  static const size_t entrySpace = Memory::doAlign(sizeof(Memory::entry_t));
    148206
     207  // get the position for the entry from the pointer the user gave us
    149208  Memory::entry_t *entry = (Memory::entry_t*)((char*)ptr-entrySpace);
    150209
     210  // let's see if the checksum is still matching
    151211  if(Memory::calcChecksum(&entry->info)!=entry->checksum){
    152212    cout << "Possible memory corruption detected!" << endl;
     
    156216  }
    157217
     218  // this will destroy the checksum, so double deletes are caught
    158219  entry->info.isUsed = false;
    159220  Memory::deleteEntry(entry);
    160221
     222  // delete the space reserved by malloc
    161223  free((char*)ptr-entrySpace);
    162224}
    163225
     226// operator that is called when the constructor throws
     227// do not call manually
    164228void operator delete(void *ptr,const char*, int) throw() {
    165229  operator delete(ptr);
     
    167231
    168232void operator delete[](void *ptr){
     233  // again difference between delete and delete[] is just in compiler bookkeeping
    169234  operator delete(ptr);
    170235}
    171236
     237// and another operator that can be called when a constructor throws
    172238void operator delete[](void *ptr,const char*, int) throw(){
    173239  operator delete(ptr);
Note: See TracChangeset for help on using the changeset viewer.