Search code examples
c++printingcrashprintfraknet

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. Luckily RakNet has two built in functions for this. GetStatistics() and 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. I modified the source code of the function and replaced the sprintf() function with std::cout and the program worked fine, just as intended.

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:

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. I just need your help to figure out why sprintf can't work as intended. I am fairly new to C++ so maybe I am missing something really obvious here. I don't know...

Thanks!


Solution

  • sprintf(buffer,...) where buffer should be large enough to contain the resulting string.

    You need something like:

    char text[1000];
    RakNet::StatisticsToString(&rns, text, 0);