我从检查堆栈损坏的 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/