[英]C++ - Program crashes when I use sprintf() function (std::cout works fine)
I am networking my program using RakNet and I want to get some network statistics during runtime. 我正在使用RakNet将程序联网,我想在运行时获取一些网络统计信息。 Luckily RakNet has two built in functions for this.
幸运的是,RakNet为此具有两个内置函数。 GetStatistics() and StatisticsToString() .
GetStatistics()和StatisticsToString() 。 However, the program crashes when I call the
StatisticsToString()
function (StatisticsToString is just supposed to convert the statistics data into a string using the sprintf function) and I have absolutely no idea why... no error... nothing. 但是,当我调用
StatisticsToString()
函数(StatisticsToString仅应使用sprintf函数将统计数据转换为字符串StatisticsToString()
时,程序崩溃,而且我绝对不知道为什么...没有错误...没有。 I modified the source code of the function and replaced the sprintf()
function with std::cout
and the program worked fine, just as intended. 我修改了该函数的源代码,并用
std::cout
替换了sprintf()
函数,该程序按预期工作正常。
My custom function for writing stats: 我用于编写统计信息的自定义函数:
void HavNetProfiler::WriteStats(RakNet::RakPeerInterface *peer)
{
if (RakNet::GetTimeMS() > nextStatTime)
{
nextStatTime = RakNet::GetTimeMS() + 1000;
RakNet::RakNetStatistics rns;
char *text;
peer->GetStatistics(peer->GetSystemAddressFromIndex(0), &rns);
RakNet::StatisticsToString(&rns, text, 0);
//printf("%s\n\n", text);
}
Snippet of source code from StatisticsToString() function: StatisticsToString()函数的源代码片段:
void RAK_DLL_EXPORT RakNet::StatisticsToString( RakNetStatistics *s, char *buffer, int verbosityLevel )
{
if ( s == 0 )
{
sprintf( buffer, "stats is a NULL pointer in statsToString\n" );
return ;
}
if (verbosityLevel==0)
{
sprintf(buffer,
"Bytes per second sent %" PRINTF_64_BIT_MODIFIER "u\n"
"Bytes per second received %" PRINTF_64_BIT_MODIFIER "u\n"
"Current packetloss %.1f%%\n",
(long long unsigned int) s->valueOverLastSecond[ACTUAL_BYTES_SENT],
(long long unsigned int) s->valueOverLastSecond[ACTUAL_BYTES_RECEIVED],
s->packetlossLastSecond*100.0f
);
//Modified std::cout solution
/*std::cout << "\nB/s sent: " << (long long unsigned int) s->valueOverLastSecond[ACTUAL_BYTES_SENT]
<< "\nB/s recieved: " << (long long unsigned int) s->valueOverLastSecond[ACTUAL_BYTES_RECEIVED]
<< "\nCurrent packetloss: " << s->packetlossLastSecond*100.0f << "\n"
<< std::flush;*/
}
The std::cout
solution is meant to be temporary as I would rather not have to edit the source code of RakNet. std::cout
解决方案是临时的,因为我不想编辑RakNet的源代码。 I just need your help to figure out why sprintf can't work as intended. 我只需要您的帮助来弄清楚为什么sprintf无法按预期工作。 I am fairly new to C++ so maybe I am missing something really obvious here.
我对C ++相当陌生,所以也许我在这里遗漏了一些明显的东西。 I don't know...
我不知道...
Thanks! 谢谢!
sprintf(buffer,...)
where buffer
should be large enough to contain the resulting string. sprintf(buffer,...)
其中buffer
应该足够大以包含结果字符串。
You need something like: 您需要类似:
char text[1000];
RakNet::StatisticsToString(&rns, text, 0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.