gpt4 book ai didi

c++ - break 语句的段错误?

转载 作者:行者123 更新时间:2023-11-30 04:07:27 26 4
gpt4 key购买 nike

我只是通过一个 switch 语句:

case RoutingMessage::FWDMESSAGE:
{
//Message Format:
//@FromNode~12~DestNode.from x to y hops .<the message>
int destID;
string changableStr, finalMessage;
string buf(iter->second);
string delim = ".";
destID = atoi(buf.substr(0, buf.find(delim)).c_str());
buf.erase(0, buf.find(delim) + delim.length());

changableStr = buf.substr(0, buf.find(delim));

stringstream sstm;
sstm << changableStr << " " << myID-3700;
changableStr = sstm.str();
buf.erase(0, buf.find(delim) + delim.length());

string theMsg = buf.substr(0, buf.find(delim));

stringstream sstm2;
sstm2 << changableStr << "." << theMsg;
finalMessage = sstm2.str();

cout << "FINAL MESSAGE: " << finalMessage << endl;

if(myID == destID)
cout << "\t\t\tMINE\n";
//PrintMessage(iter->)
else
{
neighbor.sin_port = forwardingTable.at(destID).begin()->first;
char *cstr = new char[finalMessage.length() + 1];
strcpy(cstr, finalMessage.c_str());
char* buf;
sprintf(buf, "@%d~%d~%d.%s", myID, RoutingMessage::FWDMESSAGE, destID, cstr);
SendMessage(neighbor, buf);
}
cout << "test\n";
break;
cout << "test2\n";
}

但是,当我点击 break; 时,gdb 吐出:

Program received signal SIGSEGV, Segmentation fault.
__GI___libc_free (mem=0x32317e3130373340) at malloc.c:2892
2892 malloc.c: No such file or directory.
(gdb) backtrace
#0 __GI___libc_free (mem=0x32317e3130373340) at malloc.c:2892
#1 0x00007ffff7b43cab in std::ios_base::~ios_base() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#2 0x00007ffff7b6ea13 in std::basic_stringstream<char, std::char_traits<char>, std::allocator<char> >::~basic_stringstream() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6

我从没见过这个...有人能帮忙吗?

最佳答案

看起来你正在 sprintfing 到这里未分配的缓冲区:

char* buf;
sprintf(buf, "@%d~%d~%d.%s", myID, RoutingMessage::FWDMESSAGE, destID, cstr);

关于c++ - break 语句的段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22497660/

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