2014-05-24 210 views
-1

在调试以下代码段时,我发现function = copy_string(temp_function);未初始化变量函数(仍指向0x0),即使return copycopy_string()复制到指向包含正确结果的初始化内存地址。C变量未初始化

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

什么是这种行为的原因是什么?

编辑: 固定分配问题。

+1

是什么的strlen()做的。 – this

+0

@自己你是什么意思? – IsKernel

+0

@IsKernel你没有用'malloc(sizeof(char)* length)保留足够的内存' – ouah

回答

1

您需要为空终止符保留空间。这条线:

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

应该是:

copy = malloc(length + 1); 

sizeof(char)始终为1,这样你就不会在这里需要它。另外,回想一下C中的参数是按值传递的,因此调用者看不到separate_test()内部对test_name,function等的更改。你可能想传递的指针的指针代替,就像这样:

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

@BLUEPIXY哈!接得好。我编辑了我的答案,谢谢注意。 –

0

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

1

您正在设置functionseparate_test中的其他变量的值。但是,由于它们是按值传递的,所以它确实会在调用函数中更改这些变量的值。