Thread: Reusing a string pointer question

  1. #1
    Registered User
    Join Date
    Apr 2009
    Posts
    34

    Reusing a string pointer question

    Hi,

    Would reusing a string pointer in the following way valid? I mean would the memory allocated for the constant string "some string" freed appropriately when the program quits?

    Code:
    void func()
    {
        WCHAR* pszString = L"some string";
        pszString = L"some other string";
    }
    
    int main(...)
    {
    ...
        func();
    ...
    }
    Also, since the constant string "some string" won't get stored in heap memory, when does it go out of scope? only when main quits?

    Thanks!

  2. #2
    Registered User
    Join Date
    Mar 2009
    Posts
    14
    Yes, it is valid, though you lose the address of "some string" for good when you re-assign pszString to something else. Both strings are stored in the static data area, and so go out of scope, and are properly destroyed and the memory freed, when main exits. However the scope of pszString is limited to func, so as the code is written now you can't access either of the strings outside of func.

    What is the "L" for?

  3. #3
    Registered User
    Join Date
    May 2009
    Posts
    16
    Quote Originally Posted by DirkMaas View Post
    Yes, it is valid, though you lose the address of "some string" for good when you re-assign pszString to something else. Both strings are stored in the static data area, and so go out of scope, and are properly destroyed and the memory freed, when main exits. However the scope of pszString is limited to func, so as the code is written now you can't access either of the strings outside of func.

    What is the "L" for?
    WCHARS need an L before the name to identify them as WCHARS

  4. #4
    Registered User
    Join Date
    Apr 2009
    Posts
    34
    Thank you for your answer Dirkmass. You need to use L"" when defining a wide character string literal. Wide character is a 2-byte character used to represent a UTF-16 character.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM
  2. I'm not ask for ENTIRE program, only 1 Question !
    By Th3-SeA in forum C Programming
    Replies: 10
    Last Post: 10-01-2003, 12:33 PM
  3. Another overloading "<<" problem
    By alphaoide in forum C++ Programming
    Replies: 18
    Last Post: 09-30-2003, 10:32 AM
  4. Next Question...
    By Azmeos in forum C++ Programming
    Replies: 3
    Last Post: 06-06-2003, 02:40 PM