簡體   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