我似乎在我的函数中获取堆栈转储,我分配内存。堆栈转储使用alloc
我正在向我的函数传递一个指针'** output'的数组。然后我分配足够的内存来为该内存分配一个字符串。但是,我正在获取堆栈转储。
非常感谢您的任何建议,
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++);
}
}
========================更新======== ================
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++);
}
}
在C中,从不投射malloc()的返回值。这是没有必要的(malloc()返回void *,它可以根据定义正确地转换为任何其他指针类型),并且可以隐藏错误(如果您忘记了头文件)。 – unwind 2009-06-04 10:35:10