我似乎在分配内存的函数中得到堆栈转储。
我将一个指针数组“**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++);
}
}
最佳答案
你有很多错误,但最主要的是你传递了一个 NULL 指针给 display_names:
char **new_output = 0; // null pointer
...
display_names(my_names, new_output);
display_names 然后取消引用它:
*output = (char*) malloc(sizeof("FullName: ")
+ strlen(*names_to_display)); // Allocate memory
导致折痕。
此外,上面的分配不够大——你想为字符串标记的结尾加 1,而且你似乎从来没有初始化分配的内存。此外,对字符串使用 sizeof 也是一个坏习惯 - 在这种情况下它会起作用,但您应该始终使用 strlen。
关于c - 使用 alloc 的堆栈转储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/949709/