Click here to Skip to main content
15,881,831 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am trying to create a time stamp at the beginning of text before it is sent to a RichTextBox control. When i do this any strings over two characters get messy and garbled(see below).

C++
char* Form1::get_date(void)
{
	time_t now = time(NULL);
	tm * ptm = localtime(&now);
	char buffer[32];
	// Format: Mo, 15.06.2009 20:20:00
	strftime(buffer, 32, "%a, %d.%m.%Y %H:%M:%S", ptm);
	
	return buffer;
}
Output:
žo 02.09.2013 10:14é€ Error

char* Form1::get_date(void)
{
		
	char date[80];
	time_t t = time(0);
	struct tm *tm;
	tm = gmtime(&t);
        // Format: 20:00
	strftime(date, sizeof(date), "%M:%S", tm);

	return date;
}
Output:
17:0Àî" Error


So as you can see the string is getting changed, by changing return date; to return "12:13"; i can see that the string is being changed before it ever leaves the function above to be sent to the RTB below.

C++
void Form1::updateConsole(System::String^ text)
	{
		System::String^ consoleOutput;
		consoleOutput = gcnew String(get_date());
		rtbConsole->Text += consoleOutput;
		rtbConsole->Text += " " + text;
		rtbConsole->Text += Environment::NewLine;

	}


Any ideas of how to resolve this?
Posted

You cannot return a buffer that is a local (stack) variable of your function. When the function returns the buffer is no longer valid as its memory has been released.

Solution 1: Place the buffer in the calling function and pass a pointer and length to it as parameters. Then let the called function fill the buffer.

Solution 2: Work with string class like std::string or CString, which you can use as return value.
 
Share this answer
 
Excelent, That was the perfect solution. I changed the code as shown below and it works excelent.

C++
void Form1::get_TimeStamp(char buffer[])
	{
			
		time_t now = time(NULL);
		tm * ptm = localtime(&now);
		//char buffer[32];
		// Format: Mo, 15.06.2009 20:20:00
		strftime(buffer, MAX_DATE, "[%H:%M:%S]", ptm);

	}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900