代码之家  ›  专栏  ›  技术社区  ›  Akatosh

为什么我会出现std::bad_alloc错误

  •  1
  • Akatosh  · 技术社区  · 9 年前

    我在运行下面的代码时遇到问题。每次我设置while循环以到达.eof()时,它都返回一个std::bad_alloc

    inFile.open(fileName, std::ios::in | std::ios::binary);
    
            if (inFile.is_open())
            {
                while (!inFile.eof())
                {
                    read(inFile, readIn);
                    vecMenu.push_back(readIn);
                    menu.push_back(readIn);
                    //count++;
                }
    
                std::cout << "File was loaded succesfully..." << std::endl;
    
                inFile.close();
            }
    

    如果我设置了预定的迭代次数,它运行良好,但当我使用EOF函数时失败。下面是读取函数的代码:

    void read(std::fstream& file, std::string& str)
    {
        if (file.is_open())
        {
            unsigned len;
            char *buf = nullptr;
    
            file.read(reinterpret_cast<char *>(&len), sizeof(unsigned));
    
            buf = new char[len + 1];
    
            file.read(buf, len);
    
            buf[len] = '\0';
    
            str = buf;
    
            std::cout << "Test: " << str << std::endl;
    
            delete[] buf;
        }
        else
        {
            std::cout << "File was not accessible" << std::endl;
        }
    }
    

    非常感谢您提供的任何帮助。 注意:我没有提到vecMenu是std::vector类型 菜单类型为std::list

    1 回复  |  直到 9 年前
        1
  •  1
  •   Community Mohan Dere    9 年前

    我看到的主要问题是:

    1. 您正在使用 while (!inFile.eof()) 以结束循环。看见 Why is iostream::eof inside a loop condition considered wrong? .

    2. 您没有检查是否调用 ifstream::read 在使用读入的变量之前成功。

    我建议:

    1. 更改您的版本 read 返回引用 ifstream .它应该返回 文件流 它将其作为输入。这使得可以使用调用 阅读 在循环的条件下。

    2. 检查是否调用 ifstream::阅读 在使用它们之前先成功。

    3. 打电话给 阅读 while 陈述

    std::ifstream& read(std::fstream& file, std::string& str)
    {
       if (file.is_open())
       {
          unsigned len;
          char *buf = nullptr;
    
          if !(file.read(reinterpret_cast<char *>(&len), sizeof(unsigned)))
          {
             return file;
          }
    
          buf = new char[len + 1];
    
          if ( !file.read(buf, len) )
          {
             delete [] buf;
             return file;
          }
    
          buf[len] = '\0';
    
          str = buf;
    
          std::cout << "Test: " << str << std::endl;
    
          delete[] buf;
       }
       else
       {
          std::cout << "File was not accessible" << std::endl;
       }
    
       return file;
    }
    

    inFile.open(fileName, std::ios::in | std::ios::binary);
    
    if (inFile.is_open())
    {
       std::cout << "File was loaded succesfully..." << std::endl;
    
       while (read(inFile, readIn))
       {
          vecMenu.push_back(readIn);
          menu.push_back(readIn);
          //count++;
       }
    
       inFile.close();
    }