【问题标题】:_free_dbg(block, _UNKNOWN_BLOCK); exception when I want to delete[] variable initiated with new_free_dbg(块,_UNKNOWN_BLOCK);当我想删除用 new 启动的 [] 变量时出现异常
【发布时间】:2021-04-12 04:16:59
【问题描述】:

我正在寻找解决方案,但找不到任何可以帮助我解决问题的方法。

编辑我不能在这个项目中使用 stl 库(所以 std::string、std:vector、std::cout 等都没有了)

我正在像这样启动我的二维字符数组:

char** string = new char*[MAX_MENU]; // MAX_MENU is 3 in my case
for (int i = 0; i < MAX_MENU; i++) {
    string[i] = new char[20];
}
string[0] = "Start";
string[1] = "Leaderboard";
string[2] = "Quit";

然后当我退出应用程序时,我会调用这个函数:

for (int i = 0; i < MAX_MENU; i++) {
    delete[] string[i];
}
delete[] string;

问题在于删除字符串[i]。当我不删除它时,问题不会发生,但我不想泄漏内存。

void __CRTDECL operator delete(void* const block) noexcept
{
    #ifdef _DEBUG
    _free_dbg(block, _UNKNOWN_BLOCK); // (X) - here is the exception
    #else
    free(block);
    #endif
}

我该如何解决?

【问题讨论】:

  • 使用 C++ 时,首选 std::vectorstd::string,而不是使用 newdelete。另外请发布一个minimal reproducible example 来重现问题,以便我们对其进行测试。
  • string[0] = "Start" 从字符串文字中分配指针并泄漏最初的新内存。请改用std::vector&lt;std::string&gt;&gt;
  • 好吧,我们不能为这个项目使用 stl 库.-.
  • 现在我编辑了帖子,对此感到抱歉
  • @G.M.你应该写一个答案

标签: c++ arrays c new-operator delete-operator


【解决方案1】:

根据 cmets,以下语句...

string[0] = "Start";

实际上将与字符串文字"Start" 关联的指针分配给string[0],分配给string[0] 并指向其的20 个字符的原始块丢失/泄露。

如果您真的不能使用std::vectorstd::string 等,那么您仍然可以使用例如strncpy。因此,代码将类似于...

char** string = new char*[MAX_MENU]; // MAX_MENU is 3 in my case
for (int i = 0; i < MAX_MENU; i++) {
    string[i] = new char[20];
    string[i][0] = '\0';
}
strncpy(string[0], "Start", 20);
strncpy(string[1], "Leaderboard", 20);
strncpy(string[2], "Quit", 20);

请注意,我在每个 string[i] 是新的之后立即添加了 string[i][0] = '\0',以确保空终止。

【讨论】:

    【解决方案2】:

    感谢@G.M.我找到了非常简单的解决方案

    我刚刚删除了这部分代码

    for (int i = 0; i < MAX_MENU; i++) {
        delete[] string[i];
    }
    
    for (int i = 0; i < MAX_MENU; i++) {
        string[i] = new char[20];
    }
    

    似乎没有内存泄漏,但我会让程序运行大约一个小时来检查图表

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-30
      • 1970-01-01
      • 2011-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-07
      • 1970-01-01
      相关资源
      最近更新 更多