Function behaving differently on windows than unix

I am working on a calendar program, and as part of it, I have a function that takes an integer representing days since sunday, and a cstring, and puts the date of that weekday of the current week into the string. When I compiled the code on Unix systems (under gcc), it works perfectly. However, compiling the same code under gcc on windows (Mingw install from dev-cpp), the function leaves the c-string blank.

Can anyone explain to me why the discrepancy, and how to fix it? The code in question is below:


#include <stdlib.h>
#include <stdio.h>
#include <time.h>

#define SECONDS_PER_DAY 86400

int getDate(int day, char * stringout)
{
int shift;
int weekday;
time_t timer;
char date[11];
struct tm theTime;

timer = time(NULL);
theTime = *localtime(&timer);
weekday = theTime.tm_wday;
shift = (day - weekday) * SECONDS_PER_DAY;
timer += shift;
theTime = *localtime(&timer);
strftime(stringout, 10, "%m/%d/%Y",&theTime);
stringout[10] = '\0';
printf("%s\n",stringout);
return 0;
}


Thanks!
Line 21: strftime() -- you must specify the number of characters available to write to the target array, which includes the '\0' null.
21 strftime(stringout, 11, "%m/%d/%Y", &theTime);

As a side note, this function assumes that the argument string will provide at least 11 characters in the target. You could obviate the problem by guaranteeing that the result is sufficient:
1
2
3
4
5
6
7
8
9
10
11
12
13
const char* const getDate_format = "%m/%d/%Y";
char getDate_result[11];
const char* getDate(int days_from_today)
{
	time_t     raw_time     = time(NULL);
	struct tm* current_time = localtime(&raw_time);

	raw_time += (days_from_today - current_time->tm_wday) * SECONDS_PER_DAY;
	current_time            = localtime(&raw_time);

	strftime(getDate_result, sizeof(getDate_result), getDate_format, current_time);
	return getDate_result;
}

This is, of course, only my opinion, and not the only way of doing it.

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