在调试以下代码段时,我发现function = copy_string(temp_function);
未初始化变量函数(仍指向0x0),即使return copy
从copy_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);
什么是这种行为的原因是什么?
编辑: 固定分配问题。
是什么的strlen()做的。 – this
@自己你是什么意思? – IsKernel
@IsKernel你没有用'malloc(sizeof(char)* length)保留足够的内存' – ouah