c++ - 在 C 中使用 char * 时出现错误 "debug assertation failed"

标签 c++ char heap-memory

<分区>

运行以下代码时出现的错误是“调试断言失败...表达式 _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)”。

我的 readTXT 方法需要传递一个 char* 对象,但我想让用户自己选择输入值。

char * mapName;
int main()
    {
        //load map
        int mapSelection;
        cout << "select a map";
        cin >> mapSelection;

        switch (mapSelection)
        {
        case 1:
            mapName = "walls1.txt";
            break;
        case 2:
           mapName = "walls2.txt";
           break;
        case 3:
            mapName = "maze1.txt";
            break;
        case 4:
           mapName = "maze2.txt";
           break;
        }

        map = readTXT(mapName, 8, 11);
        delete mapName;
    ...

这是 readTXT 方法的代码

double* readTXT(char *fileName, int sizeR, int sizeC)
{
  double* data = new double[sizeR*sizeC];
  int i=0;
  ifstream myfile (fileName);
  if (myfile.is_open())
  {

    while ( myfile.good())
    {
       if (i>sizeR*sizeC-1) break;
         myfile >> *(data+i);
         cout << *(data+i) << ' '; // This line display the converted data on the screen, you may comment it out. 
         if (i == 10 || i == 21 || i == 32 || i == 43 || i == 54 || i == 65 || i == 76)
         {
             cout << "\n";
         }
         i++;
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 
  //cout << i;

  return data;
}

最佳答案

你不应该这样做:

delete mapName;

因为 mapName 来自一个字符串常量。只删除你用new分配的内存。

字符串常量内置于您的程序中,不需要删除。当您使用 char* 引用一个时,您并不是在制作拷贝,因此不会引入任何删除的需要。

关于c++ - 在 C 中使用 char * 时出现错误 "debug assertation failed",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15818493/

相关文章:

javascript - 设置Node Js V8引擎堆堆栈

c++ - 在单线程应用程序中在堆栈上分配大量内存是否可以?

c++ - 从数组中提取数字的高效算法

c++ - 创建一个非预定义大小的数组?

c++ - 来自位的 HBITMAP

c++ - 配置文件在项目 C++ 中的位置

C++ Unicode 项目符号点

c - 如何使用 scanf() 在 C 中接受 char *

java - 如何从cmd永久增加芝麻存储的堆大小?

c++不使用C标准库将字符串和int转换为char *