C变量未初始化

时间:2014-05-24 16:12:49

标签: c ansi

在调试以下代码片段时,我发现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);

这种行为的原因是什么?

编辑: 固定分配问题。

3 个答案:

答案 0 :(得分:1)

您要在function中设置separate_test和其他变量的值。但是,由于它们是按值传递的,因此确实会改变调用函数中这些变量的值。

答案 1 :(得分:1)

您需要为null终止符保留空间。这一行:

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

应该是:

copy = malloc(length + 1);

sizeof(char)始终为1,因此您不需要此处。

另外,请记住C中的参数是按值传递的,因此调用者无法看到您在test_name内对functionseparate_test()等所做的更改。您可能希望将指针传递给指针,如下所示:

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);
}

答案 2 :(得分:0)

这是因为function中的seperate_test参数是临时变量。所以它需要一个随机地址,因为在调用它之前,变量被初始化为NULL。我建议在调用函数或返回函数参数之前创建一个:function = malloc(sizeof(function))

相关问题