Storing char pointers then fill it later on
Question
I'm having a small issue here, so I'm storing a char pointer ( rather an array ), in a void pointer as following:
char result[255];
CEVariable result_var(CEType::string, result);
Now the result_var is then passed on to my engine, stored as a pointer, the variable structure is then accessed later on: ( m_pData is a void*, pointing to the char array )
strcpy((char*)pVar->m_pData, "42");
But no data is written to it, and I'm sure it points to the result array, as I checked the addresses. Maybe I have gotten something wrong in my understanding of void pointers, but the following seems to work: ( Just testing )
char dest[255];
void*ptr = dest;
strcpy((char*)ptr, "asdsa");
std::cout << dest;
The result array turns into an unreadable format, most likely random memory. Maybe never written to. My question is what may the issue be?
EDIT: CEVariable::
class CEVariable
{
public:
CEVariable() {}
CEVariable(CEType t, void* mem)
{
m_Type = t;
m_pData = mem;
}
// Variable Type
CEType m_Type;
// Variable Data Ptr
void* m_pData;
};
The result does not go out of scope as all is executed in one function.
Thank you for your time.
Solution
Your CEVariable::m_pData
is only a pointer. It has no space reserved for the string.
You should first allocate some memory for the string (e.g. using new[]
), and then strcpy()
the source string to that reserved space:
// Dynamically allocate some memory with new[].
// For the string "42", it's 3 chars: '4', '2' and terminating NUL '\0'.
// For a generic string, you may want to use strlen(s)+1.
pVar->m_pData = new char[3];
// Copy string
strcpy(static_cast<char*>(pVar->m_pData), "42");
// Don't forget to release the string memory with delete[]
// when it's no longer needed.
// (e.g. in CEVariable's destructor.)
Note that in C++ you should use C++-style casts instead of C-style casts.
The problem with your stack-allocated buffer char result[255]
is that it will be destroyed when the variable goes out of scope. Instead, if you allocate the string memory with new[]
(from the heap), this memory will still be available after the scoped-ending brace }
. The memory will be released when you call delete[]
on the pointer.
OTHER TIPS
If the scope that had char result[255]
is no longer "alive", this is undefined behavior. You need to use new
to allocate heap memory, or make it static
.
In this piece of code:
char result[255];
CEVariable result_var(CEType::string, result);
If variable result
is a local variable in some function, then you need to make sure that you do not use variable result_var
once you're outside the scope of this function.