Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use a static var to "cache" the result? C++

I am using a function that returns a char*, and right now I am getting the compiler warning "returning address of local variable or temporary", so I guess I will have to use a static var for the return, my question is can I make something like if(var already set) return var else do function and return var?

This is my function:

char * GetUID()
{
   TCHAR buf[20];

   StringCchPrintf(buf, 20*sizeof(char), TEXT("%s"), 
            someFunction());

   return buf;
}

And this is what I want to do:

char * GetUID()
{
   static TCHAR buf[20];

   if(strlen(buf)!=0) return buf;

   StringCchPrintf(buf, 20*sizeof(char), TEXT("%s"), 
            someFunction());

   return buf;
}

Is this a well use of static vars? And should I use ZeroMemory(&buf, 20*sizeof(char))? I removed it because if I use it above the if(strlen...) my TCHAR length is never 0, should I use it below?

like image 681
flyout Avatar asked Nov 25 '25 21:11

flyout


1 Answers

The reason you're getting a warning is because the memory allocated within your function for buf is going to be popped off the stack once the function exits. If you return a pointer to that memory address, you have a pointer to undefined memory. It may work, it may not - it's not safe regardless.

Typically the pattern in C/C++ is to allocate a block of memory and pass a pointer to that block into your function. e.g.

void GetUID( char* buf )
{
    if(strlen(buf)!=0) return;

    StringCchPrintf(buf, 20*sizeof(char), TEXT("%s"), someFunction());
}

If you want the function (GetUID) itself to handle caching the result, then you can use a static, a singleton (OOP), or consider thread local storage. (e.g. in Visual C++)

__declspec(thread) TCHAR buf[20];
like image 132
hemp Avatar answered Nov 28 '25 15:11

hemp