계속해서 dirs_later_array를 전달하고 반환합니다. else 블록에 "new_size = ..."가 생기면 두 번째로 new_size가 2로 끝납니다. 여태까지는 그런대로 잘됐다. 내가 realloc을에게Realloc가 포인터 배열의 크기를 조정하지 않습니다.
dirs_later_array = realloc(dirs_later_array,
new_size * sizeof(struct dirs_later*));
을 할 때 sizeof의는 dirs_later_array를 들어, 포인터의 크기, 4에 남아있다. 나는 dirs_later_array [1]에 성공적으로 저장할 수 있지만 그 값은 다음에 함수에 들어갈 때 덮어 쓰게됩니다.
struct dirs_later** add_struct(const char *findme, struct dirent *dptr, struct stat *this_lstat, char *relative_path, const char *type_str, struct dirs_later **dirs_later_array) { struct dirs_later *new_dir = malloc(sizeof(struct dirs_later)); check_realloc_dirs_error(new_dir); if (strcmp(dptr->d_name, ".")) { //Dir and not same directory //Copy the relative path to the struct char *relative_path2; relative_path2 = malloc(strlen(relative_path) + 1); check_realloc_error(relative_path2); strcpy(relative_path2, relative_path); //if (strlen(relative_path) > 0) // relative_path2[strlen(relative_path) - 1] = '\0'; if (NULL != new_dir) { new_dir->findme = findme; new_dir->dptr = dptr; new_dir->st_mode = this_lstat->st_mode; new_dir->relative_path = relative_path2; new_dir->type_str = type_str; } int new_size = 0; /* //Check if this is the first element in the struct if (sizeof(dirs_later_array)/sizeof(struct dirs_later*) == 1) { new_size = 1; } */ if (dirs_later_array == NULL) { dirs_later_array = malloc(sizeof(struct dirs_later*)); //Store the directory structures or process later check_realloc_arr_error(*dirs_later_array); new_size = 1; } else { //Add directories to directories array new_size = (((sizeof(dirs_later_array) + sizeof(struct dirs_later*)))/sizeof(struct dirs_later*)); //printf("new size: %d",new_size); } dirs_later_array = realloc(dirs_later_array, new_size * sizeof(struct dirs_later*)); check_realloc_arr_error(dirs_later_array); dirs_later_array[new_size - 1] = new_dir; } return dirs_later_array; }
'realloc'은 크기를 조정하지 않고 그냥 동적 메모리를 할당합니다. 매개 변수로 cited하여 포인터에 지정합니다. –
@Als하지만 그렇습니다! 크기가 조정됩니다! –
@Als - Any는 원본 내용이 변경되지 않았 음을 보장합니다 (새로운 공간까지). –