在 C 中使用字符 * 时出现错误"debug assertation failed"



当我运行以下代码时,我得到的错误是"调试断言失败…表达_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分配的delete内存

字符串常量是内置于程序中的,不需要删除。当你提到一个使用char*的时候,你不是在复制,所以这并不需要删除。

不要删除没有从new获得的内存:

delete mapName;

删除上面的行。

最新更新