Hello,
I have written a problem to practice pointers and allocating memory.
However, I am getting a stack dump when I free the memory. Am I freeing in the correct place.
Is there anything else wrong with my program that could make it unsafe?
many thanks for any advice,
void display_names(char **names_to_display, char **output);
int main(void)
{
char *names[] = {"Luke", "John", "Peter", 0};
char **my_names = names;
char *new_output[1024] = {0};
size_t i = 0;
// Print the ordinal names
while(*my_names)
{
printf("Name: %s\n", *my_names++);
}
my_names = names; /* Reset */
display_names(my_names, new_output);
// Print the updated names
while(new_output[i])
{
printf("Full names: %s\n", new_output[i]);
i++;
}
// Free allocated memory
free(new_output);
getchar();
return 0;
}
void display_names(char **names_to_display, char **output)
{
while(*names_to_display)
{
*output = (char*) malloc(strlen("FullName: ") + strlen(*names_to_display) + 1);
if(!*output)
{
fprintf(stderr, "Cannot allocate memory");
exit(1);
}
// Copy new output
sprintf(*output, "FullName: %s", *names_to_display++);
printf("display_names(): Name: %s\n", *output++);
}
}