gpt4 book ai didi

c++ - 段错误。地址 0x0 未被堆栈、malloc 或(最近)释放

转载 作者:太空宇宙 更新时间:2023-11-04 11:27:14 25 4
gpt4 key购买 nike

我是 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);
}

任何理解这一点的人。给我简单的方向好吗?

非常感谢你提前

最佳答案

可以猜测的代码量非常少,但是,这是我的想法:

while(cityList.size()>0){
string city = cityList[cityList.size()-1];
insertMatchByCity(conn,city);
cityList.erase(cityList.end()-1);
}

如果您通过引用(可能是另一个线程)将城市发送到 insertMatchByCity,并且该线程仍未处理其数据,即它仍然持有对城市的引用。假设线程被操作系统抢占。现在,您的迭代(while 循环)将继续,作为局部范围变量的 city 将被销毁。所以,现在当该线程尝试取消引用城市时,它会导致崩溃!

应用我的取证分析:)

关于c++ - 段错误。地址 0x0 未被堆栈、malloc 或(最近)释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26206101/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com