最近,我一直试图用一个小的测试程序与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_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;
}
答案 0 :(得分:3)
/ gs选项允许运行时检测程序中的错误。删除该选项允许程序退出而不检测它,但错误仍然存在。在代码或库中的某处,堆栈上的内存被覆盖。我会尝试对代码进行二进制搜索,以查看导致错误的语句。您可能还希望始终检查所有数据库调用的返回值。
你绝对不应该禁用此选项。这样做会隐藏真正的错误,并可能使您的程序受到黑客攻击。
答案 1 :(得分:2)
确保检查方法调用的结果代码。这听起来类似于这个问题:Buffer Overrun using Mysql Connector c++因为Visual Studio的/ gs标志警告缓冲区溢出。