这是针对计算机科学数据结构类的,我们正在制作一个“内存管理器”,也就是模仿堆工作的东西。基本上,如果用户想在堆上存储东西,他们会定义一些字节数。为了在堆上存储东西,它们传递他们需要的字节数,并返回一个指向堆上至少具有该大小的区域的指针。我得到了这个工作,但我们有一个名为 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
}