vc++调试断言在程序退出时失败

VC++ debug assertion failed on program exit

本文关键字:退出 失败 程序 调试 断言 vc++      更新时间:2023-10-16

我正在尝试创建一个链表类模板(是的,我知道c++库中有一个,但我想创建自己的乐趣)。我已经跟踪了代码,直到程序退出,一切似乎都很正常。

下面是使用的代码:

list.h:

#ifndef LIST_H
#define LIST_H
#include "misc.h"
template <typename T> class CList {
private:
  class CNode {
  friend CList;
  private: T data; 
       CNode* next;
  public: CNode() : next(NULL) {}
      ~CNode() { delete [] next; }
  };
private: int length; 
         CNode* first;
public: 
  CList() : length(0), first(NULL) {}
  CList(int i_length) : first(NULL) {
    int i;
    CNode* cur = NULL;
    CNode* prev = NULL;
    if (i_length < 0) length = 0;
    else length = i_length;
    for (i=0;i<length;i++) {
      // allocate new CNode on heap
      cur = new2<CNode>();
      // attach preceding CNode pointer
      if (prev) prev->next = cur;
      else first = cur;
      prev = cur;
    }
  }
  ~CList() { delete first; }
};

misc.h

#ifndef MISC_H
#define MISC_H
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
inline void terminate( const char* message, int code ) {
  printf("nn%snn",message);
  system("pause");
  exit(code);
};
template <typename T> inline T* new2() {
  T* ret = new T;
  if (!ret) terminate("Insufficient Memory",-2);
  return ret;
}
template <typename T> inline T* new2(int num) {
  if (num <= 0) terminate("Invalid Argument",-1);
  T* ret = new T[num];
  if(!ret) terminate("Insufficient Memory",-2);
  return ret;
}

#endif

main.cpp

#include <stdio.h>
#include <stdlib.h>
#include "../Misc/misc.h"
#include "../Misc/list.h"
int main(int argc, char* argv[]) {
  //CList<int> m;
  CList<int> n(5);
  system("pause");
  return 0;
}

下面是变量"n"在"return 0;"前的断点处的样子。

http://s20.beta.photobucket.com/user/marshallbs/media/Untitled_zps52497d5d.png.html

下面是错误发生的上下文。不幸的是,现在我不能再在观察列表中查看变量"n"了。

       _mlock(_HEAP_LOCK);  /* block other threads */
    __TRY
        /* get a pointer to memory block header */
        pHead = pHdr(pUserData);
         /* verify block type */
        _ASSERTE(_BLOCK_TYPE_IS_VALID(pHead->nBlockUse));

当我为列表使用默认构造函数时没有错误。我不明白发生了什么,因为内存释放进程应该在到达第五个CNode对象时停止,该对象有一个空的"下一个"指针。它的行为就好像它试图释放一个无效的非空指针,但我不知道这是怎么发生的

我按原样构建并运行代码(从调试器),没有发现断言失败。实际上,根本没有内存释放,因为CList没有析构函数(您没有发布完整的代码吗?)

一个问题是您使用new分配next并使用delete[]释放它。这是未定义的行为。

分配:

   cur = new2<CNode>(); // new2 uses `new' and not `new[]'

回收:

  ~CNode() { delete [] next; }

将后者替换为delete next;

相关文章: