Adding two LPCWSTR variables - c++

I'm trying to add two LPCWSTR Variables as in
Shader = L"shader.fx"
Path = L"Source/Shaders/"
return Path + Shader
I've tried a thousand different ways, but my latest has been this
LPCWSTR ShaderFile = GetShader(L"shader.fx");
....
LPCWSTR GetShader(std::wstring _Shader)
{
std::wstring ShaderPath = static_cast<std::wstring>(SHADER_DIRECTORY) + _Shader;
LPCWSTR Return = ShaderPath.c_str();
return Return;
}
Now when I put a break point on the return, the value seems fine, return = Source/Shaders/shader.fx as expected. But when I F10 back into my object, the ShaderFile variable turns out to be something completely random, a bunch of what seems like arabic symbols.
Could anyone point me in the right direction of what to do? As I said, the function seems to work fine, just when i F10 through the breakpoint back into my project the variable equals something completely different

What's happening is that you're returning an address to data that's being invalidated by the return, so everything will seem fine before the function returns, but immediately after the result, it's all (at least potentially) garbage.
If at all possible, just return the std::wstring, and somewhere in the calling code call its c_str() member function when you really need it in the form of a raw buffer.
If you can't do that, and simply must return the result as a raw LPCWSTR, then you'll probably have to allocate the space dynamically:
LPCWSTR *ret = new char [ShaderPath.size()];
strcpy(ret, ShaderPath.c_str());
return ret;
Then, the calling code will need to delete [] the memory when it's no longer needed.
You really want to avoid the latter, and just return an std::wstring though. It's much simpler and cleaner, and will save the nearly inevitable problems with either deleting the buffer before you're finished using it, or else forgetting to delete it when you are done using it (still serious problems in C, but essentially unheard of in decently written C++).

The wstring.c_str() returns the internal pointer of the string.
In your case the local variable is destroyed when you exit the function and hence the pointer returned is deallocated and you get unexpected result.
Possible solution would be to copy the string using the method wcscpy()

The problem is that the c_str() method is returning a pointer into the local variable ShaderPath's memory. When the function exits, ShaderPath is destroyed, along with the data pointed to by your LPCWSTR.
Why don't you just store the variable as a wstring, and whenever you need the LPCWSTR you can call c_str()?
std::wstring GetShader(std::wstring _Shader)
{
return static_cast<std::wstring>(SHADER_DIRECTORY) + _Shader;
}
Assuming you had a function Foo(LPCWSTR path), you would use it like:
Foo(GetShader(L"shader.fx").c_str());
or
std::wstring ShaderFile = GetShader(L"shader.fx");
Foo(ShaderFile.c_str());

Related

Cannot safely delete LPTSTR allocation

Consider:
CCustomDateTime::CCustomDateTime()
{
LPTSTR result = new TCHAR[1024];
time_t _currentTime_t = time(0);
tm now;
localtime_s(&now, &_currentTime_t);
_tasctime_s(result, _tcslen(result), &now);
_currentTime = result;
delete[] result; // Error occurs here
}
CCustomDateTime::~CCustomDateTime()
{
}
__int64 CCustomDateTime::CurrentTimeAsInt64()
{
return _currentTime_t;
}
LPTSTR CCustomDateTime::CurrentTimeAsString()
{
return _currentTime;
}
I am unable to figure out the safest place to call delete[] on result.
If delete[] is ignored everything is fine, but otherwise an error occurs:
HEAP CORUPTION DETECTED at line delete[]
_tcslen(result) is not doing what you think it is.
change
_tasctime_s(result, _tcslen(result), &now);
to
_tasctime_s(result, 1024, &now);
There are a few problems with your code that I can see:
You don't check any of the function calls for errors. Don't ignore the return value. Use it to check for errors.
The second argument to _tasctime_s is the number of elements in the buffer provided. In other words, 1024. But you pass _tcslen(result) which is the length of the null-terminated string. Not only is that the wrong value, but result is at that point not initialised, so your code has undefined behaviour.
You assign a value to _currentTime, and then immediately delete that memory. So, _currentTime is a stale pointer. Any attempt to read from that memory is yet more undefined behaviour.
I don't want to tell you what your code should be, because you have only given us a tiny window into what you are trying to achieve. Dynamically allocating a fixed length array seems pointless. You may as well use automatically allocated storage. Of course, if you do want to return the memory to the caller, then dynamic allocation makes sense, but in that case then surely the caller would be responsible for calling delete[]. Since this code is clearly C++ I have to wonder why you are using raw memory allocation. Why not use standard library classes like std::string?
Looking at your update to the question, you could deallocate the memory in the destructor of your class. Personally though, I would recommend learning about the standard library classes that will greatly simplify your code.
_tcslen maps to strlen or wcslen depending on whether you are using ANSI or Unicode, respectively.
Both these functions return the length of a string, not the size of the buffer. In other words, they take a pointer to the first character of a string and continuously increment the pointer in search of a null terminator.
Calling these functions on an uninitialized buffer is undefined behavior because there's a very good chance that the pointer will get incremented out of the array bounds and elsewhere into the process' memory.

Why does fstream.open(filename) work with literal but not with generated string? [duplicate]

This question already has answers here:
scope of local variables of a function in C
(8 answers)
Closed 9 years ago.
In a DLL compiled from C++ with MS Visual Studio 2003, I'm generating a file path by getting a string from SHGetFolderPath and appending a file name, then trying to open that file for output.
I have some globals, one function to setup the file path, and another function to open the file, all shown below.
The Logger class declaration isn't shown, but it has a member declared as ofstream *ofs which is the file object created in Logger's constructor.
In constructorBase(), if I call initLogFN() to setup the file path, ofs->open fails.
However, if I comment out the initLogFN() call and uncomment the line that sets logPath to a hard-coded string literal, ofs->open succeeds.
When debugging in either case, Visual Studio correctly shows logPath as having the value "C:\Users\sleis\AppData\Roaming\Address-IT.log" before ofs->open is called.
However in the failing case, after the ofs->open call, logPath's value changes to six characters that seem random but are the same every time I run my test app.
Why do the two cases behave differently, and how can I fix the failing case?
#if defined (WIN32)
const char dirSep[]="\\";
#else
const char dirSep[]="/";
#endif
const char logFN[]="Address-IT.log";
char *logPath=0;
bool initLogFN()
{
if (logPath!=0) return false;
#if defined (_DEBUG)
#if defined (WIN32)
char path[MAX_PATH];
HRESULT result=SHGetFolderPath(NULL,CSIDL_APPDATA,NULL,SHGFP_TYPE_CURRENT,path);
if (result!=S_OK) return false;
strcat(path,dirSep);
strcat(path,logFN);
logPath=path;
return true;
#endif
#endif
return false;
}
void Logger::constructorBase()
{
if (!initLogFN()) return;
//logPath="C:\\Users\\sleis\\AppData\\Roaming\\Address-IT.log";
ofs->open(logPath,ios_base::out | ios_base::app);
if ((ofs->rdstate() & std::ifstream::failbit)!=0) {
std::cout << std::endl << "Error opening log file.";
} else if (ofs->is_open()) {
std::cout << std::endl << "Log file opened successfully.";
}
}
The array path is an automatic variable local to initLogFN. When you set logPath=path, it causes the logPath variable to point into this array. But when the function returns, that array goes out of scope, which means whatever memory it occupied may be subsequently overwritten. Now path points to garbage.
Never return a pointer to a local variable.
You essentially have three options for returning a C-style string from a function:
Have the function dynamically allocate the memory for the string, using malloc or (in C++) new. If you do this, then the caller will have to eventually call free or delete to avoid memory leaks.
Pass the char* as a parameter to the function. The caller should pre-allocate the memory for the string and then pass the pointer into the function. The function writes into the location the pointer points to.
Use a global variable, and return a pointer to that.
Of these approaches, #2 is the most common. The C and C++ standard libraries take this approach (e.g. fgets), and generally require another parameter indicating the size of the buffer passed in, so the function knows not to write past the end of allocated memory.
The disadvantage of approach #3 is that it is not reentrant. A few old Unix library functions take approach #3 (e.g. ttyname), but reentrant versions that take approach #2 were later introduced (e.g., ttyname_r).
The problem is that you are trying to reference a variable (char path[MAX_PATH]) which no longer exists.
First you create this variable in initLogFN. Then you assign logPath to point at the address of it. But outside the scope of initLogFN (aka after it returns), the memory logPath is now pointing at is complete garbage.
The reason it still looks okay in the debugger BEFORE you call the next function is because it exists on the stack. However, the stack is overwritten with the call to the next function. And your string is filled with garbage. The reason it's filled with the same six characters of garbage each time? Let's call that luck.
There are a few ways you could fix this problem.
You could dynamically allocate the character array, for example by saying char* path = new char[MAX_PATH]. If you do this, make sure you clean it up after you're done by saying delete path.
You could declare path within your constructor base, and then pass it into your initLogFN. For example, your new initLogFN would have this signature bool initLogFN(char* path), and you would call it like this (from Logger::constructorBase) char path[MAX_PATH]; initLogFN(path);
The third way would be to remove this seemingly unnecessary helper function (initLogFN) and just put that code into the constructorBase function.
The choice is yours and yours alone! Good luck! Just remember, if you don't dynamically allocate something (using new or malloc), then don't try to store a global pointer to it, and definitely don't try to reference it outside of the scope in which it was declared!
The statement logPath=path; sets the pointer logPath to point to the same location as path. As soon as the function exits, the memory for path (and thus the memory for logPath) is deallocated and the memory gets reallocated and overwritten by further function calls.
You need to allocate data for logPath and copy with strcpy the data from path to logpath to prevent that.

how to pass LPTSTR to a function and modify it's contents

I need a function that is supplied a LPTSTR and an enumerated value, constructs a string based on the value and puts it in the LPTSTR.
I've written the following function which uses an array of names indexed by an enumerated value:
bool GetWinClassName(const int &WinType, LPTSTR *className, const int bufSize)
{
bool allOk = true;
LPTSTR tempName = new TCHAR[bufSize];
_stprintf_s(tempName, bufSize, TEXT("Win%sClass"), g_WinNames[WinType]);
std::cout << (char*)tempName << std::endl;
if (FAILED(StringCchCopy(*className, (bufSize+1)*sizeof(TCHAR), tempName)))
{
allOk = false;
}
delete[] tempName;
return allOk;
}
(Originally I just had the _stprintf_s line using className instead of tempName, this has been broken up to find where the error lies.)
The above code compiles in VC2010 Express but gives an unhandled exception: "Access violation writing" to (presumably) *className when it tries to execute the StringCchCopy line.
I can get this to work by doing
className = new TCHAR[bufSize];
before calling the function (with a matching delete[] after it) but do I really need to do that each time I want to call the function?
I understand where the problem lies but not why which is hampering my efforts to come up with a workable solution. The problem appears to me to be that I can't put something in the LPTSTR (via _stprintf_s or StringCchCopy) unless I allocate it some memory by using new TCHAR[bufSize]. I've tried assigning it an intial value of exactly the same size but with the same results which is leading me to think that the memory allocation actually has nothing to do with it. Is it then somehow casting my LPTSTR into a TCHAR[]? I don't see how that's possible but at this stage, I'd believe anything.
Can someone please explain what I'm doing wrong? (Or at least where my understanding is wrong.) And a probably related question is why is my std::cout only showing the first character of the string?
wstring winClassName( int const winType )
{
return wstring( L"Win" ) + g_WinNames[winType] + L"Class";
}
But I'm just completely baffled why you have that global array of names etc.: it's probably a design level error.
do I really need to do that each time I want to call the function?
An LPTSTR value is not a string object, it is simply a pointer-to-TCHAR. If you do not allocate a buffer, where do you think the characters will go? You must make sure that the className pointer argument points to a memory buffer that you can write to. Whether you allocate a new buffer each time is up to you.
As Alf implies, a better alternative is to avoid the direct use of pointers and dynamically allocated arrays altogether, and return a string object.
why is my std::cout only showing the first character of the string?
Use std::wcout instead if UNICODE is defined.

Possible Memory Leak: new char[strlen()]

This is a fairly basic question and I am pretty sure I know the answer, but seeing as the consequence for being wrong is a segfault I figure I should ask. I have been using strlen() and the new char[] operator in the following way for quite some time now and just noticed something that threw up a red flag:
void genericCopy(char *somestring, char *someOtherString) {
someOtherString = new char[strlen(somestring)];
strcpy(someOtherString,somestring);
}
My question is, seeing as a string should be null terminated, should I be doing this as such:
void genericCopy(char *somestring, char *someOtherString) {
someOtherString = new char[strlen(somestring)+1];
strcpy(someOtherString,somestring);
someOtherString[strlen(someOtherString)] = '\0';
}
So far I have never had a problem with the first method, but that doesn't mean I'm doing it right. Since the length being return by strlen()is the number of characters in the string without the null terminator so new isn't reserving space for '/0'... At least I don't think it is.
First of all, you should know that this function of yours is pointless to write, just use strdup (if available on your system).
But yes, you need an additional byte to store the \0, so always do something like new char[strlen(somestring)+1];. However, there is no need to manually add the \0; strcpy already does this.
You should use something like Valgrind to discover this and similar bugs in your code.
There is however an additional problem in your code; your code will always leak someOtherString; it will not be returned to where you called it from. You either need to change your method to something like:
char *genericCopy(char *something) {
char *copy = new char[strlen(somestring)+1];
strcpy(copy,somestring);
return copy;
}
and then get the copy as follows:
copy = genericCopy(something);
Or you need to change your method to something like:
void genericCopy(char *something, char **copy) {
*copy = new char[strlen(somestring)+1];
strcpy(*copy,somestring);
}
and call it as:
genericCopy(something, &copy);
If you'll be using C++ you could also just change the method prototype to:
void genericCopy(char* somestring, char*& someOtherString)
and call it as:
genericCopy(something, copy);
Then someOtherString will be passed as a reference, and the new value you allocate to it will propagate outside of your method.
Yes, your suspicion is correct. You should be allocating an additional character, and making sure the copied string is null-terminated. (strcpy() itself will do this, but when someone advises to you that you switch to strncpy(), as they no doubt will (it's safer!) you'll need to be extra careful, because it is NOT guaranteed to copy the '/0'.)
If you're already using C++, though, you may be well-advised to switch to using std::string. It's often an easier, less error-prone method of manipulating character arrays.
However, here's the further problem that you need to address. You are assigning your new character array to a COPY of someOtherString. You need to make some changes:
void genericCopy(char *somestring, char **someOtherString) {
*someOtherString = new char[strlen(somestring)+1];
strcpy(*someOtherString,somestring);
(*someOtherString)[strlen(somestring)] = '\0';
}
This way you will get back the new character buffer outside your function call.

How to prevent copying a wild pointer string

My program is crash intermittently when it tries to copy a character array which is not ended by a NULL terminator('\0').
class CMenuButton {
TCHAR m_szNode[32];
CMenuButton() {
memset(m_szNode, '\0', sizeof(m_szNode));
}
};
int main() {
....
CString szTemp = ((CMenuButton*)pButton)->m_szNode; // sometime it crashes here
...
return 0;
}
I suspected someone had not copied the character well ended by '\0', and it ended like:
Stack
m_szNode $%#^&!&!&!*#*#&!(*#(!*##&#&*&##!^&*&#(*!#*((*&*SDFKJSHDF*(&(*&(()(**
Can you tell me what is happening and what should i do to prevent the copying of wild pointer? Help will be very much appreciated!
I guess I'm unable to check if the character array is NULL before copying...
I suspect that your real problem could be that pButton is a bad pointer, so check that out first.
The only way to be 100% sure that a pointer is correct, and points to a correctly sized/allocated object is to never use pointers you didn't create, and never accept/return pointers. You would use cookies, instead, and look up your pointer in some sort of cookie -> pointer lookup (such as a hash table). Basically, don't trust user input.
If you are more concerned with finding bugs, and less about 100% safety against things like buffer overrun attacks, etc. then you can take a less aggressive approach. In your function signatures, where you currently take pointers to arrays, add a size parameter. E.g.:
void someFunction(char* someString);
Becomes
void someFunction(char* someString, size_t size_of_buffer);
Also, force the termination of arrays/strings in your functions. If you hit the end, and it isn't null-terminated, truncate it.
Make it so you can provide the size of the buffer when you call these, rather than calling strlen (or equivalent) on all your arrays before you call them.
This is similar to the approach taken by the "safe string functions" that were created by Microsoft (some of which were proposed for standardization). Not sure if this is the perfect link, but you can google for additional links:
http://msdn.microsoft.com/en-us/library/ff565508(VS.85).aspx
There are two possibilities:
pButton doesn't point to a CMenuButton like you think it does, and the cast is causing undefined behavior.
The code that sets m_szNode is incorrect, overflowing the given size of 32 characters.
Since you haven't shown us either piece of code, it's difficult to see what's wrong. Your initialization of m_szNode looks OK.
Is there any reason that you didn't choose a CString for m_szNode?
My approach would be to make m_szNode a private member in CMenuButton, and explicitly NULL-terminate it in the mutator method.
class CMenuButton {
private:
TCHAR m_szNode[32];
public:
void set_szNode( TCHAR x ) {
// set m_szNode appropriately
m_szNode[ 31 ] = 0;
}
};