繁体   English   中英

使用alloc进行堆栈转储

[英]stack dump using alloc

我似乎在分配内存的函数中收到堆栈转储。

我正在向我的函数传递一个指针数组“ **输出”。 然后,我分配足够的内存以在该内存中分配一个字符串。 但是,我正在堆栈堆栈。

非常感谢您的任何建议,

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。

您无法评估* output,因为您传递了output = null (主要是******* newoutput = 0 *)。

您可以在进入sprintf循环之前,通过测试有多少个字符串以及最大的字符串变形来解决该问题,并从分配块到输出开始。

附带说明一下,您在哪里释放该块? 不要回答“但我马上要退出” ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM