【发布时间】:2012-06-15 17:21:11
【问题描述】:
我正在尝试使用 mysql connexion 从我的数据库中获取 std::string
下面是简单的代码:
sql::Statement *stmt = con->createStatement();
sql::ResultSet *res = stmt->executeQuery("SELECT * FROM test.new_table");
while (res->next()) {
std::string somestring = res->getString("idnew_table");
} //crashes here
delete res;
delete stmt;
所以,executeQuery 没问题,我进入循环,如果我中断,预期的结果会在某个字符串中。在 somestring 声明之后,我前进到循环的结尾,它在下一次迭代之前崩溃了!
这是调用堆栈:
> msvcp100d.dll!std::_Lockit::_Lockit(int kind) Line 64 + 0x14 bytes C++
msvcp100d.dll!std::_Container_base12::_Orphan_all() Line 200 C++
CM.dll!std::_String_val<char,std::allocator<char> >::~_String_val<char,std::allocator<char> >() Line 478 + 0xb bytes C++
CM.dll!std::basic_string<char,std::char_traits<char>,std::allocator<char> >::~basic_string<char,std::char_traits<char>,std::allocator<char> >() Line 755 + 0xf bytes C++
CM.dll!DAL::GetInfo() Line 45 + 0xc bytes C++
输出:
First-chance exception at 0x1038ad4a (msvcp100d.dll) in CMLauncher.exe: 0xC0000005: Access violation reading location 0xccccccd0.
Unhandled exception at 0x76f615de in CMLauncher.exe: 0xC0000005: Access violation reading location 0xccccccd0.
First-chance exception at 0x76f5016e in CMLauncher.exe: 0x00000000: The operation completed successfully.
Unhandled exception at 0x76f615de in CMLauncher.exe: 0x00000000: The operation completed successfully.
所以看起来我在 C++ 运行时库的某个地方有一些未初始化的内存...... 看起来它在 std::string 析构函数中崩溃了,这是有道理的,因为当字符串的范围完成时它会崩溃......
我最好的猜测是 libmysql 使用的是旧版本的 C++ 运行时(比如 msvcp90d.dll),并且它与新版本发生冲突......这是否有意义?
我在 windows 7 下,使用 mySQL Server 5.5,VS2010 Pro。全部为 32 位。谢谢!我很乐意发布任何需要的 mroe 信息。
编辑:在其他人阅读 DumbCoders 评论之前: MySQL Connector example 文档指定语句和结果集都必须删除。
【问题讨论】:
-
你为什么要对没有被 new 分配的对象使用 delete ?如果您没有使用 new 分配内存,则不应使用 delete。
-
因为 mysql-connexion 文档指定我必须这样做。无论如何,它在删除之前崩溃。这条评论太快了,你来不及看完全文。
-
我做了调试,这就是为什么有一个调用堆栈,我说“向前”。没有错。 dev.mysql.com/tech-resources/articles/mysql-connector-cpp.html。请停止发帖。
-
@DavidMenard
stmt和res指针是否获得合法值?尝试在循环中打印一些内容以检查它是否完全进入。 -
@DumbCoder 显然指针在库函数中是
newed。如果官方文档中的示例显示它应该是这样使用的,那么无论代码看起来多么笨拙,这就是它应该使用的方式。
标签: c++ mysql string crash std