【问题标题】:Reading %s by using %s crashes [closed]使用 %s 读取 %s 崩溃 [关闭]
【发布时间】:2015-09-19 22:01:16
【问题描述】:

我正在聊天,当有人输入“%s”或“%s%s%s”时,每个人的客户端都会崩溃,这就是我的做法。

const char* pszID = their id
const char* pszName = their name
const char* pszChatText = their raw message

if (!pszID || !pszName || !pszChatText)
return;

std::string strChat;
strChat.append("[");
strChat += pszID;
strChat.append(" :: ");
strChat += pszName;
strChat.append("] ");
strChat += pszChatText;

SendToServer(strChat.c_str());

所以如果他们进入 %s%s%s pszChatText 为 %s%s%s 并崩溃。

但我希望它像平常一样,

[A48AJV :: thegamerman3000032] %s%s%s

sendtoserver 是崩溃的,它只是一个 const char* 的 printf(),我还检查它是否为空指针

编辑:已修复指南

【问题讨论】:

  • 如果客户端在收到消息的时候崩溃了,那么这个bug就在客户端收到消息了。您粘贴的代码与处理接收消息的客户端无关。

标签: c++ string text


【解决方案1】:

听起来您将字符串作为第一个参数直接传递给printf。不要这样做。这是因为第一个参数被解析为占位符。如果您指定的占位符多于可变参数,那么您的程序将会崩溃。

而是提供"%s" 作为第一个参数,您的字符串作为第二个参数。

例如:

string chatMessage = "makeItCrash%s%s%s";
printf( "%s", chatMessage ); // program will not crash now

【讨论】:

  • 尝试使用"%s", strPushToConsole.c_str() 并且没有c_str(),但当有人将 %s 作为他们的消息时仍然崩溃,这可能是 += 我做的吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-22
  • 2012-03-11
  • 1970-01-01
相关资源
最近更新 更多