0

在我的一个项目中,我使用 cJSON 库来提取密钥。让我用代码告诉你这个问题。

代码:

char *username ="name";
void somefunction(char *msg)
{
    cJSON *tree_1 = NULL;
    char *actual = NULL;
    tree_1 = cJSON_Parse(msg);
    cJSON *name = cJSON_GetObjectItem(tree_1, "name");
    if(name)
    {
        username = cJSON_GetObjectItem(tree_1, "name")->valuestring;
        //we get here username as 'abc'
    }
}

/**
 * this function i m calling using xTaskCreate()
 * 
 */
void TaskFuntion(void* parameter)
{
    // doing something
    while (true)
    {
        printf("username %s\n",username);
        if(strcmp(username,"abc")==0)
        {
            // do something.
        }
        else
        {
            // do something.
        }
    }
    vTaskDelete(NULL);
}

问题:在这里,当我解析密钥时,我得到了"abc"预期并保存在 global 中username。一旦我得到密钥,"abc"我就会在 while 循环中做一些事情。但是在somefunction完成username对垃圾值的变量更改之后。

我了解导致此问题的一个问题是,当我检索 CJSON 引用address(指针)时的密钥时。cJSON_GetObjectItem(tree_1, "name")->valuestring; 但是问题是在解析了我保存在全局变量中的密钥并且过程完成之后,为什么它会变成垃圾。

有没有其他方法可以解决这个问题。

提前致谢

4

0 回答 0