Dereferencing pointer on heap, mscvp.dll error?? - crashes. C++

0

This is for a computer science data-structures class and we are making a "memory manager" aka something that mimicks the job of the heap. Basically, the user defines a number of bytes to have if they want to store things on the heap. To store things on the heap, they pass in the number of bytes they need and it returns a pointer to an area with at least that size on the heap. I got this working but we have a method called dump() that prints out all of these "chunks" the user has created thus far, and if the memory is free or used. This method works until I reach a certain point at which it gives me an error. Here is the struct for my node.

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

Here is the code that generates the error:

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.

My p_head is created in the constructor like so, if it helps... (p_mem exists within my .h file)

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

}
c++
memory
heap
asked on Stack Overflow Dec 7, 2012 by Zac

1 Answer

0

Weel, apparently, at some point, p_dump->p_right is null, which makes p_dump null on the next time through the loop. And since p_dump is address 0, then p_dump->sizeOfBlock is address 001C.

Between the while(true) and the cout, you should have something like:

 assert(p_dump != null);
answered on Stack Overflow Dec 7, 2012 by James Curran

User contributions licensed under CC BY-SA 3.0