gpt4 book ai didi

c++ - mysqlcppconn 程序中的内存泄漏

转载 作者:行者123 更新时间:2023-11-29 05:01:18 33 4
gpt4 key购买 nike

我有一个运行的程序占用越来越多的内存。这一直持续到整个程序崩溃。我已经将它缩小到这个部分——如果我把它注释掉,正在使用的内存就不会再增加了。

为什么这段代码会导致内存泄漏?指针是否由于某种原因没有被删除?我是否使用了错误的 executeUpdate 函数?

#include <cppconn/prepared_statement.h> // preparedStatement
sql::PreparedStatement* pstatement;
try{
for(const auto& bar : m_bars) {

std::string sql = "INSERT INTO "
+ m_table_name
+ " VALUES (' "
+ trade_platform::datetime::toString(datetime) + "', '"
+ bar.first + "', "
+ "'IB', "
+ std::to_string(bar.second.getOpen()) + ", "
+ std::to_string(bar.second.getHigh()) + ", "
+ std::to_string(bar.second.getLow()) + ", "
+ std::to_string(bar.second.getClose()) + ", "
+ std::to_string(bar.second.getVolume()) + ");";

pstatement = m_conn->prepareStatement(sql);
// prepare our statement and execute query
pstatement->executeUpdate();
}
}catch(const std::exception& e){
std::cerr << "flushToDB problem: " << e.what() << "\n";
}catch(...){
std::cerr << "unspecified flushToDB problem\n";
}

// free
delete pstatement;

最佳答案

您正在创建 sql 语句 N 次,但只有最后一个被删除。

删除每条语句会更好:

#include <memory>
...

try{
for(const auto& bar : m_bars) {

std::string sql = "INSERT INTO "
+ m_table_name
+ " VALUES (' "
+ trade_platform::datetime::toString(datetime) + "', '"
+ bar.first + "', "
+ "'IB', "
+ std::to_string(bar.second.getOpen()) + ", "
+ std::to_string(bar.second.getHigh()) + ", "
+ std::to_string(bar.second.getLow()) + ", "
+ std::to_string(bar.second.getClose()) + ", "
+ std::to_string(bar.second.getVolume()) + ");";

std::unique_ptr<sql::PreparedStatement> pstatement(m_conn->prepareStatement(sql)); // enabling RAII
// prepare our statement and execute query
pstatement->executeUpdate();

// unique_ptr wil automatically call delete on sql statement
// after pstatement leaves the scope, and c++ guarantees that
// the destructor of pstatement will be called always even in case of exception thrown
}
}catch(const std::exception& e){
std::cerr << "flushToDB problem: " << e.what() << "\n";
}catch(...){
std::cerr << "unspecified flushToDB problem\n";
}

关于c++ - mysqlcppconn 程序中的内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58769012/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com