gpt4 book ai didi

c++ - String is not null terminated 错误

转载 作者:行者123 更新时间:2023-11-28 06:35:14 25 4
gpt4 key购买 nike

我有一个 string is not null terminated 错误,虽然我不完全确定为什么。在代码的第二部分中使用 std::string 是我修复此问题的尝试之一,尽管它仍然不起作用。

我的初始代码只是使用缓冲区并将所有内容复制到 client_id[]。错误发生了。如果错误正确,则意味着我有 client_ id 或 theBuffer 没有空终止符。我很确定 client_id 没问题,因为我可以在 Debug模式下看到它。奇怪的是缓冲区也有一个空终止符。不知道出了什么问题。

char * next_token1 = NULL;
char * theWholeMessage = &(inStream[3]);
theTarget = strtok_s(theWholeMessage, " ",&next_token1);
sendTalkPackets(next_token1, sizeof(next_token1) + 1, id_clientUse, (unsigned int)std::stoi(theTarget));

里面sendTalkPackets是。我在最后一行得到一个字符串不是空终止的。

void ServerGame::sendTalkPackets(char * buffer, unsigned int buffersize, unsigned int theSender, unsigned int theReceiver)
{
std::string theMessage(buffer);
theMessage += "0";

const unsigned int packet_size = sizeof(Packet);
char packet_data[packet_size];
Packet packet;
packet.packet_type = TALK;

char client_id[MAX_MESSAGE_SIZE];


char theBuffer[MAX_MESSAGE_SIZE];
strcpy_s(theBuffer, theMessage.c_str());
//Quick hot fix for error "string not null terminated"

const char * test = theMessage.c_str();
sprintf_s(client_id, "User %s whispered: ", Usernames.find(theSender)->second.c_str());
printf("This is it %s ", buffer);
strcat_s(client_id, buffersize , theBuffer);

最佳答案

我认为问题出在这一行:

sendTalkPackets(next_token1, sizeof(next_token1) + 1, id_clientUse, (unsigned int)std::stoi(theTarget));

sizeof(next_token1)+1 总是给出 5(在 32 位平台上),因为它返回指针的大小而不是 char 数组的大小。

关于c++ - String is not null terminated 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26885388/

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