2009-06-04 73 views
1

我似乎在我的函数中获取堆栈转储,我分配内存。堆栈转储使用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++); 
    } 
} 
+0

在C中,从不投射malloc()的返回值。这是没有必要的(malloc()返回void *,它可以根据定义正确地转换为任何其他指针类型),并且可以隐藏错误(如果您忘记了头文件)。 – unwind 2009-06-04 10:35:10

回答

4

你有许多错误,但最主要的是要传递A零位指针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 

导致creash。

另外,上面的分配不够大 - 你想为字符串标记的末尾加1,并且你似乎从未初始化分配的内存。另外,在字符串中使用sizeof是一个坏习惯 - 它在这种情况下会起作用,但是您应该始终使用strlen。

+0

你好。我已经更新了我的答案。但是,我没有得到任何分配内存的堆栈转储。但是,当我从函数返回时,我得到了堆栈转储。我已经把**输出的输出声明为* output []。我不确定,但他们都是同样的事情?非常感谢。 – ant2009 2009-06-04 17:01:48

1

,因为你已经在输出已过,您无法评价*输出 = NULL(主,******* newoutput = 0 *)。

你可以通过测试你有多少字符串和最大字符串来修复它,并开始在输入你的sprintf循环之前分配块到输出

作为一个方面的评论,你在哪里释放该块?不要回答“但我正在退出......”