c++ - 调用 mysql_close 导致堆栈损坏,这是 MySQL 中的错误吗?

标签 c++ mysql stack-corruption

我从检查堆栈损坏的 Boost 测试框架中调用此代码。

我收到此错误消息: 运行时检查失败 #2 - 变量“temp”周围的堆栈已损坏。我是否成功打开了与 mysql 数据库的连接并不重要。如果我注释掉 mysql_close 调用,我就不会收到这样的消息。

我安装了 MySQL Server 5.6 并链接到这些目录:

C:\Program Files\MySQL\MySQL Connector.C 6.1\lib
C:\Program Files\MySQL\Connector.C++ 1.1\lib\opt

我正在运行我在这里找到的 DLL:

C:\Program Files\MySQL\MySQL Connector.C 6.1\lib\libmysql.dll

我想知道调用约定是否错误,因为这是一个 C++ 项目?解决这个问题的正确方法是什么?其他一切似乎都正常工作,我没有从任何其他 mysql_ 调用中得到任何堆栈损坏。

我有一个函数定义为:

void create_db(const std::string &host, const std::string &username, const std::string &password, const std::string &name)
{
    MYSQL temp;
    mysql_init(&temp);
    if (!mysql_real_connect(&temp, host.c_str(), username.c_str(), password.c_str(), NULL, 0, NULL, 0))
    {
        throw mysql_db::error(mysql_error(&temp), DETAILS, mysql_errno(&temp));
    }
    std::string query_str("CREATE DATABASE IF NOT EXISTS "+name);
    if (0 != mysql_real_query(&temp, query_str.c_str(), (unsigned long)query_str.length())) {
        mysql_close(&temp);
        throw database::error(mysql_error(&temp), DETAILS, mysql_errno(&temp));
    }
    mysql_close(&temp);
}

我可以注释掉所有内容以重现此问题,只留下:

void create_db(const std::string &host, const std::string &username, const std::string &password, const std::string &name)
    {
        MYSQL temp;
        mysql_init(&temp);
        mysql_close(&temp);
    }

mysql_close 的 MySQL 文档如下:

20.6.7.5 mysql_close() void mysql_close(MYSQL *mysql)

描述

关闭之前打开的连接。如果句柄是由 mysql_init() 或 mysql_connect() 自动分配的,则 mysql_close() 还会释放 mysql 指向的连接句柄。

所以我觉得我在这里调用mysql_close是可以的。

最佳答案

MySQL 库期望MYSQL 指针是由malloc() 在堆上分配的对象; mysql_close() 函数将最终尝试 free() 最后的指针。这对于堆栈上的对象不能正常工作。

您需要使用 malloc() 自己分配这个对象,或者允许 mysql_init() 自己分配它,例如

MYSQL *temp = mysql_init(NULL);
...
mysql_free(temp);

MYSQL *temp = malloc(sizeof(MYSQL));
mysql_init(temp);
...
mysql_free(temp);

关于c++ - 调用 mysql_close 导致堆栈损坏,这是 MySQL 中的错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30289111/

相关文章:

PHP 绑定(bind)参数() : Number of variables doesn't match number of parameters in prepared statement

mysql - 如何在Sybase SQL Anywhere 中模拟MySQL 的bit_count 函数?

c++ - 调试堆栈损坏方法

c++ - 变量 'temp' 周围的堆栈已损坏

c++ - 如何在使用 TensorRT C++ API 编写的 TensorRT 模型上运行半精度推理?

mysql - 如何从一个 ec2 到另一个 ec2 中的 SQL 数据库进行交互(连接和发送查询)?使用Python 3代码

c++ - 用作模板的类中的静态常量变量

c - 调用 OpenSSL DES_cbc_encrypt() 时堆栈损坏

c++ - 程序无法运行 OpenCV,即使其他人可以

c++ - 通过 char* 缓冲区读取 int 的行为是不同的,无论它是正数还是负数