Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

memory allocation of temporary strings

I have a question about strings or specifically about the memory used by a string. I'm using MSVC2010. Consider this piece of code:

void Test() {
    LPWCSTR String = L"Testing";
    PrintString(String);
}

void PrintString(LPWCSTR String) {
    // print String to console or similar
}

Is it safe to create and use a string in this way? Is the memory allocated for the storage of the string freed when the string goes out of scope?

like image 418
Dave Camp Avatar asked Dec 25 '22 21:12

Dave Camp


2 Answers

Yes it is safe, but actually there are no allocations ;)

The L"Testing" will be kept in read only part of your exe file (as a constant set of characters). LPWCSTR String is just a pointer to it, and it doesn't need to be destroyed/deallocated

like image 89
Michał Walenciak Avatar answered Jan 08 '23 15:01

Michał Walenciak


I'll assume that LPWCSTR is typo for LPCWSTR; a freaky Microsoft name for a pointer to a C-style string. It stands for "long pointer to constant wide string", and is an obfuscated way of writing const wchar_t*.

Is it safe to create and use a string in this way?

Like any pointer, it's safe to use as long as it points to a valid array. In this case, it points to a string literal, which is an array with a lifetime as long as the program. So this usage is safe.

If it were to point to an array that might be destroyed while the pointer were still in use, then it would not be safe.

Is the memory allocated for the storage of the string freed when the string goes out of scope?

No; the pointer will not manage memory for you. If you need to do that, use std::wstring.

like image 35
Mike Seymour Avatar answered Jan 08 '23 16:01

Mike Seymour