【发布时间】:2014-10-05 18:57:13
【问题描述】:
我对 C++ 很陌生,但我必须解决这个问题。如果您能帮我做,我们将不胜感激。
这是一种每天运行一次的 cron 程序,它一直运行到今天。但它向我显示了一个段错误。它从 mysql 获取用户信息并按城市进行匹配并插入到 mysql 上的表中。所以我运行 valgrind 以获取更多信息,如下所示。
==11897== Invalid read of size 1
==11897== at 0x4C28F52: strlen (mc_replace_strmem.c:403)
==11897== by 0x5BF614B: std::string::operator=(char const*) (in /usr/lib64/libstdc++.so.6.0.13)
==11897== by 0x4039E7: insertMatchByCity(st_mysql*, std::string) (main.cpp:156)
==11897== by 0x407DB5: main (main.cpp:759)
==11897== Address 0x0 is not stack'd, malloc'd or (recently) free'd
还有这个
==11897== LEAK SUMMARY:
==11897== definitely lost: 0 bytes in 0 blocks
==11897== indirectly lost: 0 bytes in 0 blocks
==11897== possibly lost: 321,326 bytes in 9,167 blocks
==11897== still reachable: 609,929 bytes in 1,886 blocks
==11897== suppressed: 0 bytes in 0 blocks
==11897== Reachable blocks (those to which a pointer was found) are not shown.
==11897== To see them, rerun with: --leak-check=full --show-reachable=yes
==11897==
==11897== ERROR SUMMARY: 9 errors from 9 contexts (suppressed: 6 from 6)
==11897==
==11897== 1 errors in context 1 of 9:
==11897== Invalid read of size 1
==11897== at 0x4C28F52: strlen (mc_replace_strmem.c:403)
==11897== by 0x5BF614B: std::string::operator=(char const*) (in /usr/lib64/libstdc++.so.6.0.13)
==11897== by 0x4039E7: insertMatchByCity(st_mysql*, std::string) (main.cpp:156)
==11897== by 0x407DB5: main (main.cpp:759)
==11897== Address 0x0 is not stack'd, malloc'd or (recently) free'd
==11897==
--11897--
--11897-- used_suppression: 4 U1004-ARM-_dl_relocate_object
--11897-- used_suppression: 2 glibc-2.5.x-on-SUSE-10.2-(PPC)-2a
==11897==
==11897== ERROR SUMMARY: 9 errors from 9 contexts (suppressed: 6 from 6)
Segmentation fault
消息的另一部分告诉我下面的源代码需要修改
//get open city list
vector<string> cityList;
sql = "SELECT distinct cityname FROM citylist WHERE open=1";
if(mysql_query(conn,sql.c_str())){
fprintf(stderr,"%s\n",mysql_error(conn));
exit(1);
}
res = mysql_store_result(conn);
while((row = mysql_fetch_row(res))!=NULL){
cityList.push_back(row[0]);
}
mysql_free_result(res);
//match according city
while(cityList.size()>0){
string city = cityList[cityList.size()-1];
insertMatchByCity(conn,city);
cityList.erase(cityList.end()-1);
}
任何理解这一点的人。请给我简单的指导?
非常感谢您
【问题讨论】:
-
没有产生该错误的代码的错误只是故事的一半。
-
疯狂猜测。你会这样做吗:
std::string s = 0;? -
main.cpp中哪一行是759?
-
@jrok insertMatchByCity(conn,city);是第 759 行。
-
我怀疑这个:
row[0]可以包含一个空指针,调用我上面的“疯狂猜测”错误。
标签: c++ gcc segmentation-fault malloc