C++内存分配/释放和自由空间错误

C++ Memory Allocation/Deallocation & FreeSpace Bug Error

本文关键字:自由空间 错误 释放 内存 分配 C++      更新时间:2023-10-16

我正在用C++练习内存分配和磁盘管理。我只是所有的工作..它只是看起来和看起来有点太容易了。我不确定我的指针以及我的分配和分配是否正确。我的总自由空间看起来可以工作,但它看起来太基本了。我只需要某人的编程经验。当我尝试运行此代码时,它给了我某种错误。

错误错误

请不要添加任何新的全局变量。

const int MMSIZE = 60136;
  char MM[MMIZE];
 //** Initialize set up any data needed to manage the memory
void initializeMemory(void)
{
  //**increments through the POOL_SIZE
  for (int a = 0; a < MMSIZE; a++) {
      MM[a] = 'NULL';
  }
}
// return a pointer inside the memory
// If no chunk can accommodate aSize call onOutOfMemory()
void* allocate(int size)
{
  //******NOT SURE*******
  int *p = new int;
  *p = 5;
return ((void*) 0);
}
// Free up a chunk previously allocated 
void deallocate(void* mPointer)
{
//******NOT SURE*******
  int *p = new int;
  delete p;
  p = 0;
  p = new int(10);
}
//Scan the memory and return the total free space remaining
int remaining(void)
{
//******NOT SURE*******
  int free = 0;
  for (int a = 0; a < MMSIZE; a++)
  {
      if (MM[a] < MMSIZE)
      {
          free += a;
      }
  }
  int free2 = free - MMSIZE;
return free2;
}

这段代码看起来甚至没有完成,但

 //** Initialize set up any data needed to manage the memory
void initializeMemory(void)
{
  //**increments through the POOL_SIZE
  for (int a = 0; a < MMSIZE; a++) {
      MM[a] = 'NULL';// <=== this should not even compile as the single quote should only take one character like 'x0' or 'N'
  }
}

甚至不应该编译,因为单引号应该只取一个字符,如"\x0"或"N"但是发布完整的模块,我可以为您提供更多帮助,并可能解释一些事情。

在不讨论代码的其他方面(例如内存泄漏等)的情况下,您得到的特定错误很可能来自*int_pointer = 0xDEADBEEF;行。 int_pointer等于 0 ,因为int_pointer = (long *)allocate(sizeof(long));和你的void* allocate(int size)及其return ((void*) 0);总是返回0。所以你得到的正是这个异常:尝试在地址0x00000000写入0xDEADBEEF,这是一个禁止的操作(在低地址有一些操作系统特定的东西)。