最近,我一直在尝试用 C++ 编写一个小测试程序来与 MySQL 服务器通信。我目前正在使用 MySQL Connector/C++ 作为我的 API 来连接到我的数据库服务器。我花了很长时间才让它运行起来,因为 oracle/mysql 几乎没有关于如何在 Visual Studio 10+ 中使用 connector/c++ 的文档。
最后,在一切正常之后,当应用程序尝试退出时似乎出现了一些问题。它抛出以下未处理的异常:
Unhandled exception at 0x00C62291 in mysql2.exe: Stack cookie instrumentation code detected a stack-based buffer overrun.
在研究了错误之后,我发现这是由于“安全检查”选项(/gs 编译器选项)造成的。当我禁用此编译器选项时,应用程序会正常退出。
我觉得我不应该关闭它,因为它是 Visual Studio 2012(可能还有其他版本?)
我的问题是:
- 为什么这个 /gs 编译器选项会导致未处理的异常?
- 关闭 /gs 编译器选项是否安全或可以?
这是未处理的异常指向的一段代码(在一个文件中,名为:gs_report.c):
#if defined (_M_IX86) || defined (_M_X64)
if (IsProcessorFeaturePresent(PF_FASTFAIL_AVAILABLE))
#endif /* defined (_M_IX86) || defined (_M_X64) */
__fastfail(FAST_FAIL_STACK_COOKIE_CHECK_FAILURE);
这是我的应用程序代码:
/* Standard C++ includes */
#include <stdlib.h>
#include <iostream>
/*
Include directly the different
headers from cppconn/ and mysql_driver.h + mysql_util.h
(and mysql_connection.h). This will reduce your build time!
*/
#include "mysql_connection.h"
#include "mysql_driver.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>
using namespace std;
int main(void)
{
cout << endl;
cout << "Let's have MySQL count from 10 to 1..." << endl;
try {
sql::Driver *driver;
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet *res;
sql::PreparedStatement *pstmt;
/* Create a connection */
driver = sql::mysql::get_driver_instance();
con = driver->connect("tcp://127.0.0.1:3306", "root", "MSxa5y");
/* Connect to the MySQL test database */
con->setSchema("test");
stmt = con->createStatement();
stmt->execute("DROP TABLE IF EXISTS test");
stmt->execute("CREATE TABLE test(id INT)");
delete stmt;
/* '?' is the supported placeholder syntax */
pstmt = con->prepareStatement("INSERT INTO test(id) VALUES (?)");
for (int i = 1; i <= 10; i++) {
pstmt->setInt(1, i);
pstmt->executeUpdate();
}
delete pstmt;
/* Select in ascending order */
pstmt = con->prepareStatement("SELECT id FROM test ORDER BY id ASC");
res = pstmt->executeQuery();
/* Fetch in reverse = descending order! */
res->afterLast();
while (res->previous())
cout << "\t... MySQL counts: " << res->getInt("id") << endl;
delete res;
delete pstmt;
delete con;
} catch (sql::SQLException &e) {
cout << "# ERR: SQLException in " << __FILE__;
cout << "() on line " << __LINE__ << endl;
cout << "# ERR: " << e.what();
cout << " (MySQL error code: " << e.getErrorCode();
cout << ", SQLState: " << e.getSQLState() << " )" << endl;
}
cout << endl;
return EXIT_SUCCESS;
}