c++链表中的内存泄漏(Valgrind)

C++ Memory leaks in a linked list (Valgrind)

本文关键字:Valgrind 泄漏 内存 链表 c++      更新时间:2023-10-16

我一直在通过我的链表的一些内存泄漏工作:(当前编辑3次以上,靠近底部)

错误如下:

==348== HEAP SUMMARY:
==348==     in use at exit: 32 bytes in 2 blocks
==348==   total heap usage: 17 allocs, 15 frees, 272 bytes allocated
==348== 
==348== 16 bytes in 1 blocks are definitely lost in loss record 1 of 2
==348==    at 0x4C2B1C7: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==348==    by 0x400A2A: RangeSet::RangeSet() (RangeSet.cpp:14)
==348==    by 0x4013ED: main (TestRange.cpp:16)
==348== 
==348== 16 bytes in 1 blocks are definitely lost in loss record 2 of 2
==348==    at 0x4C2B1C7: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==348==    by 0x400F54: RangeSet::Union(RangeSet const&, RangeSet const&) (RangeSet.cpp:167)
==348==    by 0x401400: main (TestRange.cpp:17)

我可以从发布的类似问题中看出,这很可能是一个问题,我正在释放"下一个"指针,但我经历并修复了这些错误(至少我尝试过),现在我只能从运行valgrind——tool=memcheck——leak-check=yes中得到这个(^)

相关代码:

RangeSet::RangeSet()
{
  // make a dummy node?
  RNode* newNode = new RNode();
  head = newNode;
  head->start = 0;
  head->end = 0;
  head->next = NULL; // newing this for memory leak??
  len=0;
} // end of constructor
// copy constructor for Union
RangeSet::RangeSet(const RangeSet &in)
{
  RNode* cur;
  RNode* nex;
  head = new RNode();
  head->start = in.head->start;
  head->end   = in.head->end;
  cur = head;
  nex = in.head->next;
  while (nex){
    cur->next = new RNode();
    cur = cur->next;
    cur->start = nex->start;
    cur->end = nex->end;
    nex = nex->next;
  }
  len = in.len;
} // end of copy constructor

// creates a pointer to new RangeSet that is the union of the two supplied RangeSets
RangeSet* RangeSet::Union(const RangeSet &alpha, const RangeSet &beta)
{
  // alpha and beta are const, so create copy
  RangeSet* copAlpha = new RangeSet(alpha);
  RNode *cursor = beta.head;
  // addRange all of beta into alpha's copy
  while (cursor != NULL){
    copAlpha->addRange(cursor->start, cursor->end);
    cursor=cursor->next;
  }
  return copAlpha;
} // end of Union

问题可能是我的RNode的构造函数?

struct RNode {
  int start, end;
  RNode* next;
  // possibly a pointer back to make it doubly linked
  RNode() {
    next = NULL;
  } 
};

编辑对不起!这是我的delete函数(我的析构函数只是调用它):

// makes the set empty
void RangeSet::deleteAllElements() 
{
 // having memory leak problems stemming from this function
 // trying to fix
  RNode *nex = head->next;
  for (RNode* cursor = head; cursor; cursor=nex){
    nex = cursor->next;
    RNode *cur = cursor;
    delete(cur);
    //delete(cursor->next); // Should I do this in a constructor for the RNode
    len--;
  }
} // end of deleteAllElements

编辑2 使用addRange和sort进行更新(由addRange在最后调用)。感谢大家一直以来的帮助!(抱歉,adrange有点长,可能有点复杂)

// addRange
void RangeSet::addRange(int rangeStart, int rangeEnd)
{
  // debug                  
  //cout << "Adding range: " << rangeStart << " to " << rangeEnd << endl;
  // li'l bit of error checking
  if (rangeStart > rangeEnd){
    cerr << "Please enter range(s) in the correct order. Exiting." << endl;
    exit(0);         
  }
  // head case
  if (len==0){
    head->start = rangeStart;
    head->end = rangeEnd;
    len++;
  // need to account for adding at beginning
  } else if (rangeStart <= head->start){
       //cout << "INSERTING AT BEGINNING" << endl;
       RNode *newNode = new RNode();                 
       newNode->start = head->start;             
       newNode->end   = head->end;  
       newNode->next  = head->next;
       head->start = rangeStart; 
       head->end   = rangeEnd;
       head->next  = newNode;                 
       len++;                 
   } else if (head->next == NULL){
       RNode *newNode = new RNode();
       newNode->start = rangeStart;
       newNode->end = rangeEnd;   
       head->next = newNode;
       len++;                 
   } else {
       // Moving past any nodes where the start is less than rangeStart
       RNode *cursor = head;
       RNode *past = cursor;
       int count = 1;
       while (cursor!=NULL && count<=len){
         if (rangeStart > cursor->start){
           //cout << rangeStart << " is > than " << cursor->start << endl;
           //cout << "DEBUG1(cursor): " << cursor->start << endl;
           //cout << "DEBUG2(past): " << past->start << endl;   
           past = cursor;
           cursor = cursor->next;
         }  
         count++;
      }
       //cout << "INSERTING POS: " << count <<  endl;
       // creating a new node to insert in middle
       RNode *newNode = new RNode();
       newNode->start = rangeStart;
       newNode->end   = rangeEnd;
       if (count == 1){       
         // add it after head (no other nodes)
         head->next = newNode;
         newNode->next = NULL;    
       } else {
         if (cursor){              
           newNode->next = cursor;
         }                  
         past->next = newNode;
       }   
       len++;
   }
  //dump();          
  sort();
} // end addRange

那么我要做的就是创建新节点并根据它的起始值将其添加到列表中,然后调用sort():

// sort function called by addRange
void RangeSet::sort()
{
  //cout << "SORTING" << endl;   
  RNode *cursor = head;
  while (cursor->next != NULL){
    RNode *curPlusOne = cursor->next;
    if (cursor->end >= (curPlusOne->start -1)){
      if (cursor->end < curPlusOne->end){
        cursor->end = curPlusOne->end;
      }
      cursor->next = curPlusOne->next;
      //cout << "NODE BEING DELETED: " << curPlusOne->start << " to " << curPlusOne->end << endl;
      delete(curPlusOne);
      len--;
    } else {
      cursor=cursor->next;
    }
  } // end while
  //dump();
} // end sort

EDIT 3张贴我的main和我的deleteRange。这次我还得到了一组不同的错误,我将在底部发布。再次感谢!

// deletes all integers from RANGESTART to RANGEEND inclusive
void RangeSet::deleteRange(int rangeStart, int rangeEnd)
{
  RNode *cursor = head;
  RNode *past = cursor;
  RNode *temp = cursor->next;
  while (cursor){
    temp = cursor->next;
    if (rangeStart <= cursor->start && rangeEnd >= cursor->end){
    // case 1: if the entire node is encompassed by what is being deleted
      if (cursor==head) { // still at head
        head = head->next;
        past = cursor;
        delete(cursor);
      } else {
        past->next = cursor->next;
        delete(cursor);
      }
      len--;
    } else if (rangeStart<=cursor->start && rangeEnd>=cursor->start && rangeEnd<=cursor->end) {
    // case 2: the rangeStart is smaller than node's rangeStart
      cursor->start = rangeEnd+1; 
      len--;
    } else if (rangeEnd>=cursor->end && rangeStart>=cursor->start && rangeStart<=cursor->end) {
    // case 3: the rangeEnd is larger than node's rangeEnd
      cursor->end = rangeStart-1;
      len--;
    } else if (cursor->start < rangeStart && cursor->end > rangeEnd){
    // case 4: the range is in the middle of a node (split)
      RNode *newNode = new RNode();
      newNode->start = rangeEnd+1;
      newNode->end = cursor->end;
      newNode->next = cursor->next;
      cursor->end=rangeStart-1;
      cursor->next = newNode;
      len--;
    }
    past = cursor;
    cursor=temp;
  } // end while
} // end of deleteRange
int main(){
   RangeSet S, T;
   S.addRange(5,10);
   S.addRange(22,33);
   S.addRange(4,6);
   T.addRange(30,35);
   RangeSet U;
   U = *RangeSet::Union(T,S);
   U.addRange(1,1);
   U.addRange(39,40);
   U.addRange(40,150);
   RangeSet B(U);
   if (B==U)
     cout << "COPY CONSTRUCTOR + OVERLOADED OPERATOR WORKED!" << endl;
   U.dump();
   cout << endl;
   U.deleteRange(1,35);
   U.deleteRange(75,100);
   U.dump();
}

这里是新的(ish,我早些时候收到它们,但我认为我已经修复了它们)错误,我收到当我运行valgrind:

==22482== Invalid read of size 8
==22482==    at 0x40122D: RangeSet::deleteAllElements() (RangeSet.cpp:237)
==22482==    by 0x400B79: RangeSet::~RangeSet() (RangeSet.cpp:47)
==22482==    by 0x401524: main (TestRange.cpp:30)
==22482==  Address 0x5a03368 is 8 bytes inside a block of size 16 free'd
==22482==    at 0x4C2A4BC: operator delete(void*) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==22482==    by 0x401261: RangeSet::deleteAllElements() (RangeSet.cpp:241)
==22482==    by 0x400B79: RangeSet::~RangeSet() (RangeSet.cpp:47)
==22482==    by 0x401500: main (TestRange.cpp:30)

这就是为什么我认为我的问题必须躺在deleteAllElements,但我仍然难住!

EDIT 4请注意,主函数是根据提供给我的框架改编的,所以如果存在问题,我不能做太多更改。

U = * RangeSet::联盟(T, S);

这条线! !那边那个!!

你正在复制返回值,然后忽略返回值,这是一个指向分配的指针,因此分配永远不会被释放。

你要做的是:

RangeSet* t = RangeSet::Union(T,S);
U = *t; // copy the returned value stored on the heap, into local varaible U not stored on the heap
delete t; // delete the returned value that is stored on the heap

好的,我认为在你的例子中你应该做的是把Union改成这样:

void Union(const RangeSet &alpha, const RangeSet &beta, RangeSet &result)
    {
      // alpha and beta are const, so create copy
      result = RangeSet(alpha);
      RNode *cursor = beta.head;
      // addRange all of beta into alpha's copy
      while (cursor != NULL){
        result.addRange(cursor->start, cursor->end);
        cursor=cursor->next;
      }
    }

则只需将main中的行更改为:RangeSet::Union(T,S,U);