繁体   English   中英

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

[英]VC++ debug assertion failed on program exit

我正在尝试创建一个链接列表类模板(是的,我知道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; }

};

杂项

#ifndef MISC_H
#define MISC_H

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

inline void terminate( const char* message, int code ) {
  printf("\n\n%s\n\n",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”在“返回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));

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

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

分配:

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

解除分配:

  ~CNode() { delete [] next; }

delete next;delete next;替换后者delete next;

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM