简体   繁体   中英

How to return a string from a function without passing any parameters in C

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.

You can do this with a static buffer, as in your own example:

char *GetCurrentTime(void)
{
    static char sVal[64];
    GetCurrentTimeEx(sVal);
    return sVal;
}

which actually does not allocate memory on the stack, but in the static region. This solution is not re-entrant and not thread-safe, but it's the only way to get the exact idiom you want in C without memory leaks.

The idiomatic solution would be to make memory allocation the responsibility of the caller and pass a buffer as an argument.

You could pass in a pre-allocated TCHAR* that GetCurrentTime() would use to put the time in:

TCHAR *GetCurrentTime(TCHAR *buf)
{
    GetCurrentTimeEx(buf);
    return buf;
}

And that call it like this:

TCHAR buf[64+1];
_stprintf(sVar,L"%s",GetCurrentTime(buf));

Or as

TCHAR buf[64+1];
GetCurrentTime(buf);
_stprintf(sVar,L"%s",buf);

Though of course that is allocated off the stack, which you might not want. On the other hand, since it is not static it will at least be re-entrant in a multi-threaded environment.

There are three ways to create an object in C - dynamically (with malloc et al), automatically (on the stack) and statically. You say you don't want to do any of these, in which case I'm afraid you are out of luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM