-1

I have some class in .h file, for example:

class Test {
public:
    static const char* superData;
private:
    static const char* getSuperData();
};

then I want to init superData in .cpp file in such a way:

const char* Test::superData = getSuperData();

But when I get superData there is only some garbage.

const char* Config::getSuperData()
{
    char username[UNLEN + 1];
    DWORD username_len = UNLEN + 1;
    GetUserName(username, &username_len);

    return username;
}

If I call getSuperData() it gives me username, not garbage. Test::superData I call in my main() function.

Vlad Ross
  • 63
  • 7

1 Answers1

2

Your initialisation is correct but your definition of getSuperdata is flawed because you are returning a pointer to a stack based array. The array no longer exists once the function has been exited, so the pointer points at garbage.

The best way to avoid this kind of problem is to avoid pointers.

#include <string>

class Test {
public:
    static std::string superData;
private:
    static std::string getSuperData();
};

std::string Test::superData = getSuperData();

std::string Config::getSuperData()
{
    char username[UNLEN + 1];
    DWORD username_len = UNLEN + 1;
    GetUserName(username, &username_len);

    return username;
}
john
  • 85,011
  • 4
  • 57
  • 81