簡體   English   中英

C變量未初始化

[英]C variable not getting initialized

調試以下代碼段時,我觀察到該function = copy_string(temp_function); 不會初始化變量函數(仍指向0x0),即使在return copy副本時,來自copy_string()副本也指向包含正確結果的初始化內存地址。

static char* copy_string(char* string)
{
    char* copy = NULL;
    uint32_t length = 0U;

    length = strlen(string);
    copy = malloc(sizeof(char) * (length +1));
    strcpy(copy, string);

    return copy;
}

static void separate_test(const char* test_name, char* function, char* scenario, char* expected_result)
{
    const char* delimiter = "__";
    char* new_test_name = NULL;
    char* temp_function = NULL;
    char* temp_scenario = NULL;
    char* temp_expected_result = NULL;
    uint32_t length = strlen(test_name);

    new_test_name = malloc(sizeof(char) * (length +1));
    strcpy(new_test_name, test_name);
    temp_function = strtok(new_test_name, delimiter);
    function = copy_string(temp_function);
    temp_scenario = strtok(NULL, delimiter);
    scenario = copy_string(temp_scenario);
    temp_expected_result = strtok(NULL, delimiter);
    expected_result = copy_string(temp_expected_result);
}

該函數使用以下參數調用:

const char* test_name = "function_name__scenario__expected_result";
char* function = NULL;
char* scenario = NULL;
char* expected_result = NULL;

separate_test(test_name, function, scenario, expected_result);

這種現象的原因是什么?

編輯:固定分配問題。

您設置的值function在和其他變量separate_test 但是,由於它們是按值傳遞的,因此確實會更改調用函數中這些變量的值。

您需要為空終止符保留空間。 這行:

copy = malloc(sizeof(char) * length);

應該:

copy = malloc(length + 1);

sizeof(char)始終為1,因此您在這里不需要它。

另外,請記住,C語言中的參數是按值傳遞的,因此調用者看不到您對test_name separate_test()中的test_namefunction等所做的更改。 您可能希望改為將指針傳遞給指針,如下所示:

const char* test_name = "function_name__scenario__expected_result";
char* function = NULL;
char* scenario = NULL;
char* expected_result = NULL;

separate_test(test_name, &function, &scenario, &expected_result);

separate_test()變為:

static void separate_test(const char* test_name, char** function, char** scenario, char** expected_result)
{
    const char* delimiter = "__";
    char* new_test_name = NULL;
    char* temp_function = NULL;
    char* temp_scenario = NULL;
    char* temp_expected_result = NULL;
    uint32_t length = strlen(test_name);

    new_test_name = malloc(length+1);
    strcpy(new_test_name, test_name);
    temp_function = strtok(new_test_name, delimiter);
    *function = copy_string(temp_function);
    temp_scenario = strtok(NULL, delimiter);
    *scenario = copy_string(temp_scenario);
    temp_expected_result = strtok(NULL, delimiter);
    *expected_result = copy_string(temp_expected_result);
}

這是因為seperate_testfunction參數是一個臨時變量。 因此,它需要一個指向它的隨機地址,因為在調用它之前,變量已初始化為NULL。 Si我建議在調用函數或返回函數參數之前先做一個: function = malloc(sizeof(function))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM