Getting confused about buffer redirection

I have this code that looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
void open_new_log(ofstream &logfile)
{
	char buffer;

	if (FILENAMES_USE_UTC)
	{
		get_utc_time(&buffer);
	}
	else
	{
		//get_local_time(&buffer);
	}

	logfile.open(&buffer); // crashes right here

}

void get_utc_time(char *buffer)
{
	SYSTEMTIME st;
	GetSystemTime(&st);
	sprintf_s(buffer, 80, "%02d%02d%02dT%02d%02dZ.log", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute);
}


It's making the program crash when it gets to logfile.open, with this message:
Unhandled exception at 0x104c8d4d (msvcp90d.dll) in xxxx.exe: 0xC0000005: Access violation reading location 0x6f6c2eaa.

In debug mode with variable watching, "buffer" works out to 50, and "&buffer" works out to "20091102T2121Z.log" which is what I want the file to be called.

So, I have two questions.
1: Why is this crashing, and how do I fix it? I'm making some very simple mistake here - what is it?
2: Is there a better way to go about doing what I'm trying to do?
A single char is not a buffer. You probably want something like char buffer[19];
(Your filenames are 18 characters long.)

You must of course also fix the buffer references:
get_utc_time(buffer);

logfile.open(buffer);

Finally, on line 22, you are using the non-standard function sprintf_s(), which provides some safety by specifying the maximum number of characters to fill. As it is, you have specified 80, which is more than buffer contains.

You should specify the same number as is the number of characters in buffer. The recommended way of doing this is to provide that information as argument:
1
2
3
4
5
6
void get_utc_time(char *buffer, size_t size)
{
	SYSTEMTIME st;
	GetSystemTime(&st);
	sprintf_s(buffer, size, "%04d%02d%02dT%02d%02dZ.log", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute);
}
and
 
get_utc_time(buffer,sizeof(buffer));

BTW, I fixed an error in your first format specifier -- as you want a four-digit date value the specifier needs to be "%04d".

Hope this helps.
Topic archived. No new replies allowed.