Reputation: 18276
I'm writing a C++ code with returns some data, the problem is: my const char is losing it value each time I call it from another file. I don't have idea what's happening.
My code on ProcClient.h
virtual void reportWorkflowError(unsigned int workflow,
const dp::String& errorCode) {
char message[1000];
snprintf(message, 1000, "Workflow: %s ERROR: %s", workflowToString(
workflow).utf8(), errorCode.utf8());
printf("[%s]", message);
errorInfo = message;
}
virtual const char * getErrorInfo() {
return errorInfo;
}
[Workflow: DW_FULFILL ERROR: E_ADEPT_NO_TOKEN]
[Workflow: ERROR: E_ADEPT_NOT_READY]
//two errors was thrown, and the errorInfo should has the last
On Services.cpp I start a "workflow", and if it throws an error the listener above is called, and after that I should get tha lastError pointer.
//g_drmClient is the ProcClient
bool RMServices::startFullfilment(dp::String acsm) {
//Do things
g_drmClient->getProcessor()->startWorkflows(dpdrm::DW_FULFILL);
size_t count = g_drmClient->getProcessor()->getFulfillmentItems();
printf("Number of items fulfilled: %d\n", count);
bool returnValue = !g_drmClient->hasError();
if (!returnValue)
lastError = g_drmClient->getErrorInfo());
printf("[%s]", lastError);
return returnValue;
}
Here it prints: [\æ¾°Ô¯£ ¯|æ¾\æ¾er of items fulfer of ite]
What's happening?
Upvotes: 1
Views: 1811
Reputation: 61457
You're putting message
on the stack. Maybe you want it to be static
, or better an instance variable.
Upvotes: 1
Reputation: 34655
char message[1000];
is a local variable residing on stack and goes out of scope on return of reportWorkflowError
. So,
errorInfo = message; // errorInfo is simply pointing to garbage on method return.
Do some thing on these lines -
void className::foo()
{
char stackVariable[] = "abcdef" ;
classVariableCharPointer = new char[ sizeof(stackVariable) + 1 ] ;
strcpy( classVariableCharPointer, stackVariable ) ;
}
Also remember to deallocate the classVariableCharPointer
in the destructor using delete[]
.
Upvotes: 8
Reputation: 67345
Yikes, you can't do that.
As soon as reportWorkflowError
returns, all local variables are destroyed. This includes message
, which returnValue
points to.
A better approach would include making returnValue
a character array, and calling srtrcpy()
to copy the local data to the member variable. This way, the copy would still exist after message
is destroyed.
Upvotes: 2