-
March 31st, 2006, 11:12 PM
#1
Convert char[100] to LPTSTR
HI All ,
i have a function whose return type is LPTSTR.
LPTSTR GetValidName()
{
char buf [100];
return buf;
}
i have removed a few lines from the function.
As u can see buf is a local variable and will not be available after the function exits.
THe compiler issues a warning for the above code.
I don't want to change the return type to a CString or a string.
what extra code should i write for the function to be appropriate.
Thanks
-
April 1st, 2006, 04:50 AM
#2
Re: Convert char[100] to LPTSTR
Boris Karadjov
Brainbench MVP for Visual C++
http://www.brainbench.com/
-
April 1st, 2006, 05:30 AM
#3
Re: Convert char[100] to LPTSTR
the problem is with returning.
char can be a TCHAR also but it will be a local variable. and after returning the scope ends.
how do we solve this ?
-
April 1st, 2006, 06:55 AM
#4
Re: Convert char[100] to LPTSTR
Following implementation should not be used by multiple threads without locking, because the static variable is shared:
Code:
/*
Not thread safe function, 'cause it uses a static variable.*/
LPTSTR GetValidName() {
static TCHAR buf [100];
return buf;
}
If you have multi-threaded calls to this function, I can suggest other implementation.
Best regards,
-
April 1st, 2006, 10:47 AM
#5
Re: Convert char[100] to LPTSTR
Originally Posted by Kris_V
the problem is with returning.
Correct.
Originally Posted by Kris_V
char can be a TCHAR also but it will be a local variable. and after returning the scope ends.
But, not necessarily so... (else, why would people use type TCHAR at all?) It depends on the pre-processor macros in use.
TCHAR can also be wchar_t - a wide character - when _UNICODE is defined... Anyways, do you really need to return a LPTSTR? That scenario seems avoidable here.
In general, convert a LPSTR (i.e. char*) to LPTSTR (i.e. TCHAR*) using conversion class CA2T.
Like this -
Code:
CA2T pszConvertedString (buf);
// Use pszConvertedString as a LPTSTR
Originally Posted by Kris_V
how do we solve this ?
Allocate memory on the heap using new, copy the buffer to this memory, and return that pointer. So, an extension to that conversion code above would be -
Code:
LPTSTR GetValidName()
{
char buf [100] = {0}; // Remember to copy a string to this buffer!
CA2T pszConvertedString (buf);
TCHAR * pszAllocatedReturnBuf = new TCHAR [_tcslen (pszConvertedString) + 1];
_tcscpy (pszAllocatedReturnBuf, pszConvertedString);
// Caller must free
return pszAllocatedReturnBuf;
}
Last edited by Siddhartha; April 1st, 2006 at 10:59 AM.
-
April 1st, 2006, 11:07 AM
#6
Re: Convert char[100] to LPTSTR
another way is simply send pointer to array:
Code:
void GetValidName(char *buf, int len)
{
//do someting with buf ( just make sure you dont setting/reading value above len )
}
// usage
char buf[MAX_PATH]={0};
GetValidName(buf,sizeof(buf));
Cheers
-
April 2nd, 2006, 02:27 AM
#7
Re: Convert char[100] to LPTSTR
Originally Posted by Siddhartha
Allocate memory on the heap using new, copy the buffer to this memory, and return that pointer.
This is fine, but has potential problems of how to deallocate. Especially, if this function is exported by a DLL or such. For one, the function has to be documented saying it allocates memory, and also what form of memory allocation was used, so the caller can use the proper deallocation routine.
Also, in case of DLLs, the module that allocated also has to deallocate. So, you would now have to provide a routine to deallocate.
All this , if this is being called from another module. But just wanted to point it out.
-
April 2nd, 2006, 04:04 AM
#8
Re: Convert char[100] to LPTSTR
Originally Posted by kirants
This is fine, but has potential problems of how to deallocate. Especially, if this function is exported by a DLL or such.
Well... This function isn't exported - according to the problem statement in the OP. I suggested that solution given the problem statement of returning a LPTSTR.
However, lets not ignore this line -
Originally Posted by Me
Anyways, do you really need to return a LPTSTR? That scenario seems avoidable here.
Good that you make that point... GS' suggested way would be the thing to do.
Last edited by Siddhartha; April 2nd, 2006 at 04:54 AM.
-
April 2nd, 2006, 11:26 AM
#9
Re: Convert char[100] to LPTSTR
Originally Posted by Siddhartha
I suggested that solution given the problem statement of returning a LPTSTR.
Agree. The OP started off with the statement that changing the function signature wasn't an option, so there is not much one can suggest
-
April 3rd, 2006, 07:23 AM
#10
Re: Convert char[100] to LPTSTR
Those were good amount of info gurus....
i felt what Bornish suggested as appropriate (using a static variable).
but he also said that in a multithreaded environment extra care has to be taken.
Bornish, can u suggest what needs to be done in a multithreaded environment ?
Thanks once again for the inputs
-
April 3rd, 2006, 07:37 AM
#11
Re: Convert char[100] to LPTSTR
http://www.codeguru.com/forum/newrep...eply&p=1364659
Originally Posted by Kris_V
Those were good amount of info gurus....
i felt what Bornish suggested as appropriate (using a static variable).
but he also said that in a multithreaded environment extra care has to be taken.
Bornish, can u suggest what needs to be done in a multithreaded environment ?
Thanks once again for the inputs
If multiple threads may call that function at the same time, then it is not a good idea to use a static local variable which can be changed by one thread while used in another thread. If such static variable exists, the function implementation should assure proper usage by implementing a locking mechanism (critical section, semaphore, mutex, RAII lock...) while using this shared static variable. Locking can be time expensive, thus is recommended to be avoided. If calls to this function are from one thread only, then keep the static variable. Else, either temporary lock calls, or use per thread variables. Thread Local Storage (TLS) is quite recommended for such situations.
Best regards,
-
April 3rd, 2006, 07:38 AM
#12
Re: Convert char[100] to LPTSTR
Actually, you need to explain why this -
Originally Posted by Kris_V
i felt what Bornish suggested as appropriate (using a static variable).
...Was appropriate?
Using a static array would actually not be my recommended way of doing it.
(Although, in a single threaded scenrio it would work just as fine.)
In my opinion, this -
Originally Posted by Kris_V
he also said that in a multithreaded environment extra care has to be taken.
...Is by far the greatest drawback not existent in other methods.
Last edited by Siddhartha; April 3rd, 2006 at 07:51 AM.
-
April 3rd, 2006, 07:51 AM
#13
Re: Convert char[100] to LPTSTR
Originally Posted by Siddhartha
Actually, you need to explain why this - ...Was appropriate?
Using a static array would actually not be my way of doing it.
In my opinion, this - ...Is by far the greatest drawback not existent in other methods.
Well Sid, let me explain:
- Imagine this being a private method of a thread class... or a derived class from one MFC class (also single-threaded implementation)... then a static local will suffice and removes the overhead of releasing memory after usage. Moveover, could be faster by not allocating and deallocating memory everytime the function is called.
- Imagine this function being used in retrieving error messages in a multi-threaded environment. Per-thread variables are perfect solution for it. Each thread can store and retrieve its own errors without overwriting or locking. Such variables will be allocated when a thread starts and released when the thread ends... not every time a function is called.
But, everyone is entitled to an oppinion.
Regards,
-
April 3rd, 2006, 08:04 AM
#14
Re: Convert char[100] to LPTSTR
Originally Posted by Bornish
Well Sid, let me explain...
Actually, the motive was pretty evident.
However, what you point out as advantages are actually the method's undoing.
Originally Posted by Bornish
Imagine this being a private method of a thread class... or a derived class from one MFC class (also single-threaded implementation)... then a static local will suffice and removes the overhead of releasing memory after usage.
Private member... ?
Sounds like you just stepped on a minefield.
Rather than have a private member that returns a static buffer instantiated within it, I would have preferred that the buffer be a static private member too.
Originally Posted by Bornish
Moveover, could be faster by not allocating and deallocating memory everytime the function is called.
I dont think one should worry about performance here, because -- Memory allocated to strings are typically released. Should a programmer be expected to treat one particular string pointer differently? This may be possible inside one function - but, not maintainable outside it (the OP's case).
- If a class returns a string pointer that wasn't previously allocated for, likelyhood is that the client would be tempted to release. That would be consistent. However, this would crash on a static pointer.
- What if Func1 returns a pointer returned by Func2 that returns your static string pointer? Till what level should one worry about not releasing a pointer?
I favour maintainability, and reliability to performance.
Also, I typically believe in measuring performance before I comprimise any of those two for it.
Of course, this is my opinion.
-
April 3rd, 2006, 08:23 AM
#15
Re: Convert char[100] to LPTSTR
Maybe the function return type should be changed from LPTSTR to LPCTSTR for ppl like you to understand how to use that function.
Originally Posted by Siddhartha
Rather than have a private member that returns a static buffer instantiated within it, I would have preferred that the buffer be a static private member too.
The only difference between having a local static variable declared in the private member function and a private member variable is localization (lazy initialization, or create on request). I prefer localization. Also, I prefer not having a class defined with a lot of junk of intermediar variables used in processing, even if their lifetime is longer (as static member data have).
In the end, I'd rather take the time to implement per-thread variables for as many reasons I can think of:
- thread safe
- speed optimization
- can be dynamically reallocated (if required)
- returned as const will not confuse anyone (and produce crashes or memory leaks)
Best regards,
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|