I have a memory allocation question. If I declare a char* within an else block that means the char* is destroyed when the else block is done executing. The else block is located in a while loop so it will iterate many times. However, what if the char* declared in the else block is aliased to a malloc'd variable as seen in the below example. My question is how do I fee something like this? I feel as though if I free the temp char* variable, I will cause a segmentation fault because I will free the variable I want to keep as well. If that is the case, I'm at a loss for where the free statement goes.
char* print_path = NULL;
(snip)
(while)
else{
char* temp_path = print_path;
int temp_size = strlen(temp_path)+strlen(file_name(child->fts_path))+1;
print_path = (char*)malloc(temp_size);
strcpy(print_path, temp_path);
strncat(print_path, file_name(child->fts_path), strlen(file_name(child->fts_path)));
printf("%s:\n\n", print_path);
}
(snip)
I would like to point out that I do free print_path at the end of the program after I know it will not be executed again. However, it is the intermediary executions of the loop that I would like to free. Any help would be appreciated. Thanks!