我犯了一个低级的C++的逻辑错误

自己犯了一个低级错误。留作警示。

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <stdlib.h>
#include <time.h>

struct MyNode
{
    int num;
    std::vector<int> theBeg;
    std::vector<int> theEnd;
};

void GenerateFile(std::string fileName)
{// 模拟一个有17W行数据的配置文件。
    std::ofstream configFile(fileName);
    if (configFile.is_open() == false)  return;
    srand((int)time(NULL));
    for (int i = 0; i < 170000; ++i)
        configFile << (rand() % 5 + 3) << std::endl;
}

void ReadFile(std::string fileName)
{// 先将每一行的配置信息转化到Node中,再将Node存储起来。
    std::ifstream ifs(fileName, std::ios_base::in | std::ios_base::binary);
    if (!ifs)  return;
    static std::vector<MyNode> theStorage;//存储配置信息的存储器。
    MyNode node;//重复使用的结构体。
    std::string line;
    while (getline(ifs, line))
    {
        node.num = atoi(line.c_str());
        //这里错了,每次重新使用结构体时,应当先清理结构体。这里应当先对vector执行clear操作。
        for (int i = 0; i < node.num; ++i)
        {
            node.theBeg.push_back(node.num);
            node.theEnd.push_back(node.num);
        }
        theStorage.push_back(node);
    }
    std::cout << theStorage.size() << std::endl;
}

int main()
{
    std::string fileName = "D:/config.txt";
    GenerateFile(fileName);
    ReadFile(fileName);
    return 0;
}
//Unhandled exception at 0x74EEC41F in vc_bad_alloc.exe: Microsoft C++ exception: std::bad_alloc at memory location 0x0034EC14.
//我写了一个程序,结果出现了std::bad_alloc异常。原因找了好久,甚至怀疑到了std库了。
//结果发现,是vector内的元素个数猛增,然后耗尽了内存。
//自己犯了一个很低级的逻辑错误。我将自己犯错的代码抽离出来,形成了上面的例子。
完。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值