0

Why does my comportstr get changed in this code to a garbage value? I don't understand how my char array could change values if nothing about it is altered. There is nothing else between those two print statements.

int main(int argc, char* argv[])
{  
    char comportstr[10];
    sprintf(comportstr,"COM%d",COMPORT_NUM);
    if(DEBUGGING) fprintf(stderr,"str is: %s\n", comportstr); //prints str is: COM3
    sprintf(curtime , "%s" , currentDateTime());
    if(DEBUGGING) fprintf(stderr,"str is: %s\n", comportstr); //prints str is: ;32
}

Here's what currentDateTime does. It doesn't modify comportstr at all.

// Gets current date/time, format is YYYY-MM-DD.HH;mm;ss
const std::string currentDateTime() 
{
    time_t     now = time(0);
    struct tm  tstruct;
    char       buf[80];
    tstruct = *localtime(&now);
    // Visit http://www.cplusplus.com/reference/clibrary/ctime/strftime/
    // for more information about date/time format
    strftime(buf, sizeof(buf), "%Y-%m-%d.%H;%M;%S", &tstruct);

    return buf;
}
4

2 回答 2

1
sprintf(curtime , "%s" , currentDateTime());

The currentDateTime function returns a std::string, but %s is for C-style strings only. You want currentDateTime().c_str(). Your compiler should have given you a warning.

于 2013-08-16T22:47:31.563 回答
1

In your currentDateTime() function you are returning a std::string which is passed to sprintf()'s vararg interface. That doesn't work as you can't pass standard layout types to vararg interfaces. That is, the second call to sprintf() results in undefined behavior.

You can avoid the problem by using

sprintf(curtime , "%s" , currentDateTime().c_str());

... or, actually,

strcpy(curtime, currentDateTime().c_str());
于 2013-08-16T22:48:02.547 回答