c++ - char* 丢失数据

标签 c++ c pointers string

我正在编写一个返回一些数据的 C++ 代码,问题是:每次我从另一个文件调用它时,我的 const char 都会丢失它的值。我不知道发生了什么。

我在 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;
}

[工作流程:DW_FULFILL 错误:E_ADEPT_NO_TOKEN]

[工作流程:错误:E_ADEPT_NOT_READY]

//抛出了两个错误,errorInfo应该是最后一个

在 Services.cpp 上,我启动了一个“工作流”,如果它抛出错误,则会调用上面的监听器,之后我应该得到 lastError 指针。

//g_drmClient即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;
}

这里打印: [\æ¾°Ô¯£ ¯|æ¾\æ¾ 件元素]

发生了什么事?

最佳答案

char message[1000];

是驻留在堆栈上的局部变量,在 reportWorkflowError 返回时超出范围。所以,

errorInfo = message; // errorInfo is simply pointing to garbage on method return.

在这些行上做一些事情-

void className::foo()
{
    char stackVariable[] = "abcdef" ;
    classVariableCharPointer = new char[ sizeof(stackVariable) + 1 ] ;

    strcpy( classVariableCharPointer, stackVariable ) ;
}

还记得在析构函数中使用 delete[] 释放 classVariableCharPointer

关于c++ - char* 丢失数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5489976/

相关文章:

c++ - 宏参数上的 Foreach 宏

C程序(Linux): get command line output to a variable and filter data

c - 如何将 C 指针递增 2

c - 取消引用指向不完整类型的指针 - 指向 char* 的指针出错

c++ - 分配和删除指针数组

c++ - 为什么在传递列表作为参数时模棱两可?

c++ - 库中的新建和删除运算符覆盖

c++ - 如何创建将 Class<T> 转换为 Class<U> 的函数,其中 T 和 U 是任意数字类型?

c - 调用 fopen 或 open 时使用什么编码?

c++ - 如何将 int 和 int* 传递给函数来定义变量