Hello,
I seem to be getting a stack dump in my function where I am allocating memory.
I am passing an array of pointers '**output' to my function. And then I allocate enough memory to assign into that memory a string. However, I am getting a stack dump.
Many thanks for any suggestions,
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 = 0;
while(*my_names)
{
printf("Name: %s\n", *my_names++);
}
my_names = names; /* Reset */
display_names(my_names, new_output);
// Display new output
while(*new_output)
{
printf("Full names: %s\n", *new_output++);
}
getchar();
return 0;
}
void display_names(char **names_to_display, char **output)
{
while(*names_to_display)
{
// Stack dump here
*output = (char*) malloc(sizeof("FullName: ") + strlen(*names_to_display)); // Allocate memory
// Copy new output
sprintf(*output, "FullName: %s", *names_to_display++);
printf("display_names(): Name: %s\n", *output++);
}
}
======================== Updated ========================
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[] = {0};
size_t i = 0;
while(*my_names)
{
printf("Name: %s\n", *my_names++);
}
my_names = names; /* Reset */
display_names(my_names, new_output);
// Stack dump here.
while(*new_output[i])
{
printf("Full names: %s\n", *new_output[i]);
i++;
}
getchar();
return 0;
}
void display_names(char **names_to_display, char **output)
{
while(*names_to_display)
{
*output = malloc(strlen("FullName: ") + strlen(*names_to_display) + 1); // Allocate memory
// Copy new output
sprintf(*output, "FullName: %s", *names_to_display++);
printf("display_names(): Name: %s\n", *output++);
}
}