在堆上取消引用指针,mscvp.dll错误? - 崩溃。 C ++

时间:2012-12-07 22:31:42

标签: c++ memory heap

这是针对计算机科学数据结构类的,我们正在制作一个“内存管理器”,它可以模仿堆的工作。基本上,如果用户想要将内容存储在堆上,则用户定义了多个字节。要将内容存储在堆上,它们会传入所需的字节数,并返回指向堆上至少具有该大小的区域的指针。我得到了这个工作,但我们有一个名为dump()的方法,打印出用户迄今为止创建的所有这些“块”,以及内存是免费还是使用的。这个方法有效,直到我达到一个给出错误的点。这是我的节点的结构。

struct Node
{
    Node* p_right;
    Node* p_left;
    int sizeOfBlock;
    bool isFree;
};

以下是生成错误的代码:

void MemoryManager::dump()
{
      Node* p_dump = p_head;    //Stores pointer with which we will loop through nodes

       int block_num = 1;   //Stores the number of the block we are at

       while( true )
       {
         cout << "\tBlock " << block_num << ": "    //Crashes here
         << (p_dump->sizeOfBlock) << " bytes ";

          if( p_dump->isFree )
              cout << "(free)\n";
          else
              cout << "(used)\n";
          block_num++;      //Increase the block num

          if( p_dump->p_right->p_right == 0 ) //If we've found the second to last node
              break;
          else
               p_dump = p_dump->p_right;     //Or else, we move the pointer

         }
 }

Unhandled exception at 0x5c7cfb8a (msvcp100d.dll) in MemoryManager.exe: 0xC0000005: Access violation reading location 0x0000001c.

我的p_head是在构造函数中创建的,如果它有帮助...(p_mem存在于我的.h文件中)

MemoryManager::MemoryManager(int numBytes)
{
//Constructor

p_mem = new char[sizeof(Node)*2 + numBytes];

p_head = (Node*)p_mem;      //Create the head node
p_tail = (Node*)(p_mem + sizeof(Node)+ numBytes); //Create the tail node

p_head->sizeOfBlock = numBytes; //Sets the size
p_tail->sizeOfBlock = 0;//Sets the size

p_head->p_right = p_tail; //Sets pointer
p_head->p_left = 0; //Sets pointer

p_tail->p_right = 0;    //Sets pointer
p_tail->p_left = p_head; //Sets pointer

p_head->isFree = true;      //Sets free to true
p_tail->isFree = false; //Sets free to false

}

1 个答案:

答案 0 :(得分:0)

显然,在某些时候,p_dump->p_right为空,这使得p_dump在下一次循环时变为空。由于p_dump是地址0,因此p_dump-&gt; sizeOfBlock是地址001C。

while(true)cout之间,你应该有:

 assert(p_dump != null);