다음 코드 조각을 디버깅 할 때 return copy
복사본에서 copy_string()
의 복사본이 올바른 결과를 포함하는 초기화 된 메모리 주소를 가리킬지라도 function = copy_string(temp_function);
은 변수 함수 (여전히 0x0을 가리킴)를 초기화하지 않는다는 것을 관찰했습니다.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);
이 문제의 원인은 무엇입니까?
편집 : 고정 할당 문제.
()는 않습니다. – this
@self 그게 무슨 소리 야? – IsKernel
@malloc (sizeof (char) * length)로 충분한 메모리를 예약하지 않은 @IsKernel – ouah