mysqlcppconn程序中的内存泄漏

泰勒

我有一个运行的程序,它占用的内存越来越多。这一直持续到整个程序崩溃为止。我将其范围缩小到本节-如果我将其注释掉,则所使用的内存不再增加。

为什么这段代码会给我带来内存泄漏?是否由于某种原因未删除指针?我使用了错误的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";
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章