0

Ill start with an example of source code (that i modified for clarity so ignore variables like "someLetter"):

wchar_t *someFunction()
{
    wchar_t str[1024] = L"";

    for (int i = 0; i < 50; i++)
    {
        str[i] = someLetter;
    }

    str[51] = L'\0';

    return str;
}

The above code simply adds wchars to w_char array and when for loop is ended, it ends the array with L'\0'. Variable ret should hold the string. However, when I execute the code below, i get nothing (empty string).

wchar_t *result = someFunction();
wcout << result << endl;

This is where it gets weird. If i execute the code mentioned all above, I get nothing. BUT if I add wcout << str << endl; in someFunction(), everything seems to be working fine i.e. code below does what its supposed to do.

wchar_t *result = someFunction();
wcout << result << endl;

TL:DR Code below doesnt print out "result". Instead it prints out nothing and result is blank. The problem is fixed if I add wcout << str<< endl; to someFunction(). Why is that and how can I avoid that.

wchar_t *result = someFunction();
wcout << result << endl;
GrubyStack
  • 35
  • 3

2 Answers2

2

You are returning a pointer to automatic storage that goes out of scope when someFunction ends, so there is no correct behavior; it is undefined what will happen if you access a variable after it's gone out of scope. If you really need to return a wchar_t*, you'll need to either use a static array, pass a pointer to a buffer into someFunction, or dynamically allocate memory (and make the caller responsible for freeing that memory). The best thing to do would probably be to use std::wstring instead of raw wchar_t*s.

Miles Budnek
  • 28,216
  • 2
  • 35
  • 52
1

This code cannot work as you return the address of a local variable. The memory of wchar_t str[1024] is freed until someFunction() returns to the caller.

Sidenode: It should be str[50] = L'\0'; and not str[51] = L'\0'

To get you code working you might either use a std::wstring and return a copy of it or allocate the memory for str on the heap using new[] and delete[] it later on.

You should probably get a bit more familiar with C++ before asking questions like this.

Chris
  • 1,226
  • 1
  • 12
  • 26
  • -1 for the last sentence. It is not your job to judge the level of knowledge of our users. If you think, that particular question is to 'nooby' for you - don't answer it. – Mateusz Grzejek Jul 28 '15 at 18:45
  • Well I did not intend to judge the knowledge of the user that asked this questions, but rather tell that this code violates a "basic rule" of C(++). I assume that there are quite a lot of questions similar to this one that got downvoted. But nevermind. – Chris Jul 28 '15 at 19:01