Pass char[N] param to thread - c++

i have a variable declared as
char myvariable[N] = "blablabla"
and i need to pass it to a thread
DWORD MyThread(LPVOID lpdwParam)
i tried to cast inside the thread function the lpdwParam in char* but it doesn't work. How can i fix it?
EDIT 1
Here the complete part of code
char myvariable[16];
GetDlgItemTextA(hDlg, IDC_IPADDRESS, &myvariable[0], 16);
myThreadHandle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)MyThread, (LPVOID)&myvariable, 0, &myThreadId);
DWORD MyThread(LPVOID lpdwParam)
{
char *myvariable2 = (char *)lpdwParam;
....
}
EDIT 2
Doesn't work means that myvariable2 doesn't contains the text of myvariable
EDIT 3
char *myvariable = new char[16];
GetDlgItemTextA(hDlg, IDC_IPADDRESS, myvariable, 16);
myThreadHandle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)MyThread, (LPVOID)myvariable, 0, &myThreadId);
and the thread function:
char *myvariable2 = (char *)lpdwParam;

If you're doing something like this:
// ...
char myvariable[N] = "blablabla";
HANDLE hThread=CreateThread(NULL, 0, MyThread, (LPVOID)myvariable, 0); // however you should use beginthread to avoid troubles with the CRT
// ...
DWORD MyThread(LPVOID lpdwParam)
{
char * mystring = (char *)lpdwParam;
// ...
return 0;
}
and you don't get the correct characters by reading mystring, my guess is that, being myvariable allocated on the stack, it goes out of scope before MyThread gets the chance to run, thus you get the same kind of problems you encounter when you return a pointer to a local variable.
The solution would be to allocate dynamically your string:
// ...
char * myvariable = new char[N];
*myvariable=0;
strncat(myvariable, "blablabla", N); // this is equivalent to what the nonstandard strlcpy would do
HANDLE hThread=CreateThread(NULL, 0, MyThread, (LPVOID)myvariable, 0); // however you should use beginthread to avoid troubles with the CRT
// ...
DWORD MyThread(LPVOID lpdwParam)
{
char * mystring = (char *)lpdwParam;
// ...
// when you're done with mystring, remember to free it; even better, use a smart pointer
delete [] mystring;
// ...
return 0;
}
By the way, notice that, as already said in the snippets, if you plan to use CRT functions inside your newly created thread you shouldn't use CreateThread directly, but you should instead use the _beginthread/_beginthreadex functions, because otherwise some CRT per-thread structures may not get initialized correctly.
Addendum
i edited my code to use new char[16] but it doesn't work. When i cast the variable from LPVOID to char* inside the thread function i get only strange symbols
If you changed the code so that myvariable is now a pointer, you should remove the & from the call to CreateThread; & was superfluous when it was used with the array (in that case just using its name was enough), but now that myvariable is a pointer it is plain wrong, since using it on myvariable will provide the address of myvariable instead of the address stored in myvariable.
Long story short, remove that ampersand.

If your doing c++ casting, you will need to use const char* var = reinterpret_cast<const char*>(lpdwParam);. Just be careful though, if its a stack string, it'll probably pass out of scope before the thread uses it, if its a static string, you should use const to preventing any accidental overwriting of data

Related

Will CString's ReleaseBuffer release Shell Allocated CoTaskMemAlloc String?

I believe, from viewing this article, I can safely use CStrings to store the returned string results of certain Windows API functions.
For example, I can do the following (not my code, from the article I linked above):
//GetCurrentDirectory gets LPTSTR
CString strCurDir;
::GetCurrentDirectory(MAX_PATH, strCurDir.GetBuffer(MAX_PATH));
strCurDir.ReleaseBuffer();
GetCurrentDirectory allocates the data in the "regular" way. I know I could also use an STL wstring to do this as well.
Now my question is, can I safely do this?
int main()
{
CString profileRootPath;
HRESULT result = SHGetKnownFolderPath(FOLDERID_Profile, 0, nullptr, (PWSTR*)&profileRootPath);
wcout << profileRootPath.GetString();
profileRootPath.ReleaseBuffer();
Sleep(10000);
return 0;
}
According to SHGetKnownFolderPath's MSDN page, the data output by SHGetKnownFolderPath needs to be de-allocated with a call to CoTaskMemFree. Is the call to ReleaseBuffer invalid because of this? Or will that work properly? Is it not a good idea to use any string class in this case and just use a plain C style array to hold the data, and then use CoTaskMemFree on the array? If the code is invalid, what is the most correct way to do this?
With ATL the code snippet might be as simple as:
CComHeapPtr<WCHAR> pszPath;
HRESULT result = SHGetKnownFolderPath(FOLDERID_Profile, 0, nullptr, (PWSTR*) &pszPath);
CString sPath(pszPath);
wcout << sPath.GetString();
~CComHeapPtr will do CoTaskMemFree going out of scope, and CString constructor will take the value as const WCHAR*.
Without CComHeapPtr you can do it like this:
WCHAR* pszPath = nullptr;
HRESULT result = SHGetKnownFolderPath(FOLDERID_Profile, 0, nullptr, (PWSTR*) &pszPath);
CString sPath(pszPath);
CoTaskMemFree(pszPath);
wcout << sPath.GetString();
GetCurrentDirectory simply takes your memory pointer to store the string to, so it makes sense to use stack variable because it has zero initialization and cleanup cost. If you need a string, you can build it from stack character array - this eliminates necessity in ReleaseBuffer call:
TCHAR pszPath[MAX_PATH];
GetCurrentDirectory(_countof(pszPath), pszPath);
CString sPath(pszPath);
The answer to my question is simply no, which I figured it would be, since CoTaskMemAlloc is a special way to allocate memory. I'll just stick with the regular way to do things.
int main()
{
WCHAR* profileRootPath = nullptr;
HRESULT result = SHGetKnownFolderPath(FOLDERID_Profile, 0, nullptr, &profileRootPath);
wcout << profileRootPath;
CoTaskMemFree(profileRootPath);
Sleep(10000);
return 0;
}

Temporary function arguments that last during scope containing function call

Consider a typical function that fills in a buffer:
const char* fillMyBuffer( const char* buf, int size );
Suppose this function fills the buffer with some useful data, that I want to use almost immediately after the call, and then I want to get rid of the buffer.
An efficient way of doing this is to allocate on the stack:
doStuff();
{
char myBuf[BUF_LEN];
const char* pBuf = fillMyBuffer( myBuf, BUF_LEN );
processBuffer( pBuf );
}
doOtherStuff();
So this is great for my library because the buffer is allocated on the stack - being essentially no cost to allocate, use and discard. It lasts the entire scope of the containing braces.
But I have a library where I do this pattern all the time. I'd like to automate this a little. Ideally I'd like code that looks like this:
doStuff();
{
// tricky - the returned buffer lasts the entire scope of the braces.
const char* pBuf = fillMyBufferLocal();
processBuffer( pBuf );
}
doOtherStuff();
But how to achieve this?
I did the following, which seems to work, but I know is counter to the standard:
class localBuf
{
public:
operator char* () { return &mBuf[0]; }
char mBuf[BUF_LEN];
};
#define fillMyBufferLocal() fillMyBuffer( localBuf(), BUF_LEN );
As a practical matter, the buffer is lasting on the stack during the entire lifetime of the containing braces. But the standard says that the object only has to last until the function returns. E.g. technically its just as unsafe as if I'd allocated the buffer on the stack inside the function.
Is there a safe way to achieve this?
I would generally recommend your original solution. It separates the allocation of the buffer from filling it. However, if you want to implement this fillMyBufferLocal alternative, it will have to dynamically allocate the buffer and return a pointer to it. Of course, if you return a raw pointer to dynamically allocated memory, it's very unclear that the memory should later be destroyed. Instead, return a smart pointer that encapsulates the appropriate ownership:
std::unique_ptr<char[]> fillMyBufferLocal()
{
std::unique_ptr<char[]> buffer(new char[BUF_LEN]);
// Fill it
return buffer;
}
Then you can use it like so:
auto buffer = fillMyBufferLocal();
processBuffer(buffer.get());
I do not think you should want to do this. It just makes the code harder to understand.
Automatic storage duration means that when an object goes out of scope, it is destroyed. Here you want trick the system into something that behaves like creating an object with automatic storage duration (i.e. allocates on the stack), but without respecting the corresponding rules (i.e. without being destroyed when returning from fillMyBuffer()).
The closest, meaningful thing you can do in my opinion is to use a global buffer that fillMyBuffer() can reuse, or let that buffer be a static variable inside fillMyBuffer(). For instance:
template<int BUF_LEN = 255>
const char* fill_my_buffer()
{
static char myBuf[BUF_LEN];
// Fill...
return myBuf;
}
However, I strongly suggest reconsidering your requirements, and either:
Keep using the solution you are currently adopting (i.e. transparently allocate on the stack); or
Allocate the buffer dynamically inside fillMyBuffer() and return a RAII wrapper (like a unique_ptr) to this dynamically allocated buffer.
UPDATE:
As a last, desperate attempt, you could define a macro that does the allocation and the invocation of fill_my_buffer() for you:
#define PREPARE_BUFFER(B, S) \
char buffer[S]; \
const char* B = fill_my_buffer(buffer, S);
You would then use it this way:
PREPARE_BUFFER(pBuf, 256);
processBuffer(pBuf);
You could write a class that contains a stack-based buffer and converts to char const *, e.g.
void processBuffer(char const * buffer);
char const * fillMyBuffer(char const * buffer, int size);
int const BUF_LEN = 123;
class Wrapper
{
public:
Wrapper(char const * (*fill)(char const *, int))
{
fill(&m_buffer[0], m_buffer.size());
}
operator char const * () const { return &m_buffer[0]; }
private:
std::array<char, BUF_LEN> m_buffer;
};
void foo()
{
Wrapper wrapper(fillMyBuffer);
processBuffer(wrapper);
}

how to set char * value from std string (c_str()) not working

i dont know but this not working for me im getting garbege value when i try to set char * value from function that returns std string :
string foo()
{
string tmp ="dummy value";
return tmp;
}
char* cc = (char *) foo().c_str(); // if i remove the casting im getting error
// when i print the cc i get garbage
printf("%s",cc);
The lifetime of the data pointed to by cc is the same as the lifetime of the string it came from (at best - if you modify the string it's even shorter).
In your case, the return value of foo() is a temporary that is destroyed at the end of the initialization of cc.
To avoid the compilation error in char *cc = foo().c_str() you shouldn't cast to char*, you should switch to const char *cc, since const char* is what c_str() returns. That still doesn't solve the main problem, though.
The simplest fixes are:
printf("%s", foo().c_str()); // if you don't need the value again later
const string s = foo();
const char *cc = s.c_str(); // if you really want the pointer - since it's
// in the same scope as s, and s is const,
// the data lives as long as cc's in scope.
string s = foo();
printf("%s", s.c_str()); // if you don't store the pointer,
// you don't have to worry about it.
std::cout << foo(); // printf isn't bringing much to this party anyway.
The result of foo is a temporary object that gets destroyed by the end of char * cc = ... line. Store it in constant reference:
const string& cc = foo();
printf ("%s", cc.c_str());
Pass a memory location to foo() and have foo modify that:
void foo (string* _out_newStr)
{
_out_newStr->assign("dummy string"); //This is wrong -> _out_newStr = "dummy string";
return;
}
Then when you are using the "c_str()" function of the string object you will return a const char* value, as already pointed out.
The code-snippet invokes undefined behavior, because the temporary std::string created from the call is destroyed at the end of the expression but cc which is pointing to the destroyed object, is still used even after that.
How about:
printf("%s", foo.c_str() );
Or better still, forget about using character pointers.

const char* in my class has junk character(s) after it's returned from function

Class:
class myclass {
public:
myclass(void);
const char* server;
private:
char pidchar[6];
int pidnum;
};
The function
myclass parseINI(const char* file)
{
myclass iniOptions;
CSimpleIniA ini;
ini.SetUnicode();
ini.LoadFile(file);
const char* server = ini.GetValue("", "server", "");
iniOptions.server = server;
std::cout << server << "\n"; // Prints the correct value here
fflush(stdout);
return iniOptions;
}
Calling it from the main function
int _tmain(int argc, TCHAR* argv[])
{
myclass options;
options = parseINI("myapp.ini");
std::cout << options.server << "\n"; // It prints junk here
return 0;
}
What did I do wrong?
The const char* returned by GetValue() probably belonged to the ini object. When you exited the parseIni() function, ini went out of scope and was destroyed, which could mean your pointer is no longer valid.
Try using a std::string for the server member type instead of const char*.
It looks like you are using memory that is released when CSimpleIniA goes out of scope in parseINI.
const char* server = ini.GetValue("", "server", "");
iniOptions.server = server;
Copy the value that is returned into a new memory block before you return from the parseINI function.
string server = ini.GetValue("", "server", "");
iniOptions.server = new char[server.length() + 1];
std::copy(server.begin(), server.end(), iniOptions.server);
iniOptions.server[server.length()] = 0;
const char* server = ini.GetValue("", "server", "");
This value is falling out of scope when the function terminates, so when you assign the value of that pointer to your object's server pointer, the place in memory they point to is having its memory freed off the stack at the end of the function, and it's then overtaken by other things.
Using a std::string or even just a char[] will be preferred to just fix the problem with the least amount of changes, as they will by assigned the actual value and not a location in memory like pointers.
What you really should do is look up referential transparency, though. That will prevent problems like this from occurring ever again
I's guess that the lifetime of the data pointed to by the char* returned from CSimpleIniA::GetValue() is the same as the CSimpleIni object itself. So when ini is destructed, the pointer returned from GetValue() becomes invalid. (I've never used CSimpleIni, and haven't looked at the docs carefully enough to know for sure, but that's what the behavior points to).
I'd suggest changing myclass::server to be a std:string object and set it using something like:
iniOptions.server = std::string(server);
which will give the myclass::server object it's own copy of the string data.
The way you are using class as a function returned data type in C++ is totally wrong.
In C++ there are 2 kinds of data type: value type, reference type.
class belongs to second one; From a function you can return a value type data or a pointer of any data.But you cann't retun a entity of a reference type. Because a entity of a reference type will be released right after the code reached out of the scope which the entity is defined.
You can do in either way:
1:
define parseINI as:
myclass* parseINI(const char* file)
{
myclass* iniOptions = new myclass();
........
return iniOptions;
}
and then use it like this:
myclass* options = parseINI("myapp.ini");
2:
define parseINI as:
void parseINI(myclass& options, const char* file)
{
........//asigne value to options's members
}
and then use it like this:
myclass options;
parseINI(options,"myapp.ini");
3:
Do what you did, but add a asignment method (operator=) to myclass
The problem is that the local variable server points to a character buffer returned by ini.GetValue(), which is destroyed when paraseINI() returns.
One way to fix this is to allocate a new buffer yourself and copy the characters.
const char* server = ini.GetValue("", "server", "");
int length = strlen(server) + 1; // length of the string +1 for the NULL character.
delete [] iniOptions.server; // free the old buffer
iniOptions.server = new char[length]; // allocate your own buffer
strncpy(iniOptions.server, server, length); // copy the characters
For this to work you have to make myclass::server non-const, and you have to initialize it to NULL in the constructor and delete it in the destructor.
A better way to deal with this situation would be use std::string instead of char * for muclass::server. This way std::string would take care of memory management for you, and the code would be exception-safe.
If you make muclass::server an std::string, then you simply do
const char* server = ini.GetValue("", "server", "");
iniOptions.server = std::string(server);
And you do not have to do anything with it in the constructor or the destructor.
iniOptions is located on the stack and disposed automatically when the function returns. You should allocate it on heap using new()

Can I use a static var to "cache" the result? C++

I am using a function that returns a char*, and right now I am getting the compiler warning "returning address of local variable or temporary", so I guess I will have to use a static var for the return, my question is can I make something like if(var already set) return var else do function and return var?
This is my function:
char * GetUID()
{
TCHAR buf[20];
StringCchPrintf(buf, 20*sizeof(char), TEXT("%s"),
someFunction());
return buf;
}
And this is what I want to do:
char * GetUID()
{
static TCHAR buf[20];
if(strlen(buf)!=0) return buf;
StringCchPrintf(buf, 20*sizeof(char), TEXT("%s"),
someFunction());
return buf;
}
Is this a well use of static vars? And should I use ZeroMemory(&buf, 20*sizeof(char))? I removed it because if I use it above the if(strlen...) my TCHAR length is never 0, should I use it below?
The reason you're getting a warning is because the memory allocated within your function for buf is going to be popped off the stack once the function exits. If you return a pointer to that memory address, you have a pointer to undefined memory. It may work, it may not - it's not safe regardless.
Typically the pattern in C/C++ is to allocate a block of memory and pass a pointer to that block into your function. e.g.
void GetUID( char* buf )
{
if(strlen(buf)!=0) return;
StringCchPrintf(buf, 20*sizeof(char), TEXT("%s"), someFunction());
}
If you want the function (GetUID) itself to handle caching the result, then you can use a static, a singleton (OOP), or consider thread local storage.
(e.g. in Visual C++)
__declspec(thread) TCHAR buf[20];
It's OK if your code is single threaded. The buffer will be set to contain all zeros when the function is entered for the very first time, so there is no need to explicitly set its contents to zero. But these days all code eventually tends to become multi-threaded, so I would not do this, if I were you.
What you should do instead is allocate buf dynamically using new, and then return it. But be aware that the caller would be responsible for deallocating the memory.
Better yet, use std::string instead of char *.
You could do that, but it won't be thread-safe. You should also be careful with what you do with the result, since you can not store it between subsequent calls to the function (without copying it, of course).
You should also initialize the static variable to the empty string.
This is how I would do it.
It caches; it does not rely on the buffer being 0.
It does have the implicit assumption that 'buf' will be identical from thread to thread, which is not (to my knowledge) correct. I would use a global for that purpose.
//returns a newly allocated buffer, every time. remember to delete [] it.
char * GetUID()
{
static TCHAR buf[20];
static bool run = false;
TCHAR ret_mem = new TCHAR[20];
if(run)
{ return ret_mem; }
//do stuff to the buf
//assuming - dst, src, size.
memcpy(ret_mem, buf, 20);
run = true;
return ret_mem;
}