user2619824
user2619824

Reputation: 478

Why is this array of chars changing value when another function is called?

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;
}

Upvotes: 0

Views: 143

Answers (2)

Dietmar Kühl
Dietmar Kühl

Reputation: 153840

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());

Upvotes: 1

David Schwartz
David Schwartz

Reputation: 182779

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.

Upvotes: 1

Related Questions