【问题标题】:C++ Memory Allocation/Deallocation & FreeSpace Bug ErrorC++ 内存分配/释放和 FreeSpace 错误错误
【发布时间】:2016-06-02 05:15:38
【问题描述】:

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

Bug Error

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

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;
}

【问题讨论】:

  • 你认为这段代码为什么有用?
  • 我不认为 OP 声称如此 - 看起来 OP 正在练习和试验内存分配。
  • 我不知道你用的是什么编译器,但是在g++下它不能编译。 MM[a] = 'NULL'; 无效。 char MM[MMIZE]; 也不是。请发布实际编译的代码。你也没有main()。
  • 我对 Studio 不熟悉,但您应该可以让它告诉您发生访问冲突异常的行号。
  • 您在函数return ((void *)0); 中的void* allocate(int size) 正在尖叫Access Violation writing location 0x00000000。

标签: c++ memory-management allocation


【解决方案1】:

即使是一个示例,这段代码看起来也没有完成,但是

 //** 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' 但是发布完整的模块,我可以为您提供更多帮助,也许还可以解释一些事情。

【讨论】:

  • 添加到我的 main.cpp 文件中
  • 它是一个多字符文字,具有int 类型和实现定义的值。所以这会给出 多字符字符常量 和 隐式常量转换溢出 警告,但会编译。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2017-03-22
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-29
    相关资源
    最近更新 更多