我的代码报错terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc,我写的代码如下:#include "mainwindow.h" #include "ui_mainwindow.h" #include <QtWidgets> #include <QResizeEvent> #include <QDebug> #include <QThread> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); replotTimer = new QTimer; ui->plot->setOpenGl(true); ui->plot->setNoAntialiasingOnDrag(true); mXDataTol = new QVector<double>; mYDataTol = new QVector<double>; mXDataTol->reserve(10000000); mYDataTol->reserve(10000000); CreateChart(); } MainWindow::~MainWindow() { delete ui; } void MainWindow::CreateChart() { ui->plot->addGraph(); ui->plot->graph(0)->setPen(QPen(QColor(100,149,237))); mData = ui->plot->graph(0)->data()->coreData(); ui->plot->xAxis2->setVisible(true); ui->plot->xAxis2->setTickLabels(false); ui->plot->yAxis2->setVisible(true); ui->plot->yAxis2->setTickLabels(false); connect(ui->plot->xAxis, SIGNAL(rangeChanged(QCPRange)), ui->plot->xAxis2, SLOT(setRange(QCPRange))); connect(ui->plot->yAxis, SIGNAL(rangeChanged(QCPRange)), ui->plot->yAxis2, SLOT(setRange(QCPRange))); ui->plot->setInteractions(QCP::iRangeDrag|QCP::iRangeZoom|QCP::iSelectPlottables); ui->plot->yAxis->setRange(-1.5,1.5); ui->plot->xAxis->setRange(0,10000000); ui->plot->yAxis->setLabel("数据"); ui->plot->xAxis->setLabel("个数"); for (int i=0;i<10000000;i++) { mXDataTol->append(i); if(i<5000000) mYDataTol->append(0); else mYDataTol->append(QRandomGenerator::global()->bounded(1.00)); } ui->plot->graph(0)->setData(*mXDataTol,*mYDataTol,true); }
时间: 2024-04-20 12:27:08 浏览: 216
这个错误通常表示你的程序在运行过程中无法分配足够的内存空间。由于你的程序中有大量的内存分配,这可能是由于你的程序在分配内存时没有正确释放内存所导致的。查看你的代码,你在构造函数中分配了两个 QVector<double> 实例,每个实例都预留了 10,000,000 个元素的空间。这将需要大约 160 MB 的内存空间。如果你在程序执行过程中创建多个这样的实例并且没有及时释放内存,就会导致内存不足的错误。你可以尝试使用 std::vector 来代替 QVector,并且只在需要时分配内存。你还可以使用 C++11 中的 unique_ptr 或 shared_ptr 来自动管理内存,以避免内存泄漏的问题。
相关问题
qt报错 terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc
这个错误通常是因为程序尝试分配比系统可用内存更多的内存导致的。解决方法有以下几种:
1. 检查代码中是否有内存泄漏,尤其是在循环中分配内存时一定要记得释放。
2. 调整程序中分配内存的大小,尽量使用较小的内存空间。
3. 尝试在分配内存时使用 try-catch 块,以捕获可能的 bad_alloc 异常,并对其进行处理。
4. 检查系统内存使用情况,看看是否可以增加系统内存大小。
5. 如果你的程序需要大量的内存,可以考虑使用虚拟内存技术,将部分内存转移到硬盘上。
希望这些方法能够帮到你。
使用QCustomPlot 绘制千万点时报错terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc
报错 "terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc" 表示内存分配失败,很可能是因为在绘制千万点时,QCustomPlot 试图分配太多的内存而导致的。
为了解决这个问题,您可以考虑使用以下方法:
1. 优化数据:在使用 QCustomPlot 绘制大量数据时,您可以考虑将数据进行优化,例如降采样、数据压缩等,以减少绘图时需要处理的数据量,从而降低内存使用量。
2. 使用分块绘制:将数据分为多个块,每次只绘制部分数据,可以减少内存使用量并提高绘图性能。您可以使用 QCustomPlot 的 `setRangeDrag()` 和 `setRangeZoom()` 函数来实现分块绘制。
3. 使用 OpenGL 绘图:QCustomPlot 支持使用 OpenGL 进行绘图,这可以大大提高绘图性能并减少内存使用量。您可以使用 QCustomPlot 的 `setOpenGl()` 函数来启用 OpenGL 绘图。
总之,在绘制千万点时,由于需要处理大量数据,很容易导致内存分配失败。您可以通过优化数据、使用分块绘制或使用 OpenGL 绘图等方法来减少内存使用量并提高绘图性能。
阅读全文
相关推荐














