I want to write a function that simply returns a string so I can do this:
TCHAR sVar[256] = {0};
_stprintf(sVar,L"%s",GetCurrentTime());
I can't implement this functionality with the following function b/c memory is freed before returning the value:
TCHAR *GetCurrentTime(void)
{
TCHAR *sVal;
sVal = (TCHAR *) calloc(64+1, sizeof(TCHAR));
GetCurrentTimeEx(sVal); // Populates
free(sVal);sVal=NULL;
return sVal;
}
and I can't do this function because there's a memory leak if I don't remember to free the memory in the calling program, which defeats the purpose of having a simple function return a char string:
TCHAR *GetCurrentTime(void)
{
TCHAR *sVal;
sVal = (TCHAR *) calloc(64+1, sizeof(TCHAR));
GetCurrentTimeEx(sVal);
return sVal;
}
and I don't want to declare memory off of the stack.:
TCHAR *GetCurrentTime(void)
{
static TCHAR sVal[64];
GetCurrentTimeEx(sVal);
return sVal;
}
(here is the function that gets the time):
DWORD GetTime(TCHAR *sCurrentTime)
{
TCHAR sTime[9] = {0};
if (_tstrtime_s(sTime, 9) == ERROR_SUCCESS)
{
INT i;
for (i=0;i<=4;i++)
sCurrentTime[i] = sTime[i];
return 1;
}
else
return 0;
}
I searched but could not find an answer to this pretty common question. Can someone help me? Thanks.
TCHAR,_stprintf,GetCurrentTime,GetCurrentTimeEx,DWORD, and_tstrtime_sare not defined in either Standard C or POSIX. If they are not defined by you in your own (not showed) code, you're unnecessarily locking yourself to the implementation you use. Also don't cast the return value ofcalloc: it is not needed and may hide errors.void writeToMyBuffer(char *buf, int buflen)could do the job. You allocate memory outside the function and just give a pointer to that region. Another way would be to use a global variable.