c - 使用 alloc 的堆栈转储

标签 c

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

我将一个指针数组“**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/

相关文章:

python - 是否可以打开 PyGTK 对象?

c - 在 thrd_t 上调用 pthread 函数是否合法?

c - 如何在内核模块的相同偏移量中预留内存

c - If .. else number is smaller than, unreachable 代码

c++ - 必须做什么才能将程序转换为强大的 OpenMP 感知版本?

c - 标题与。静态库

计算 __m256i 字中的前导零

c - 在 C 中使用 Malloc 添加两个数组 HW

c - 使用 popen 时静默 tcpdump 的输出

c++ - 在不执行脚本的情况下调用 Lua 函数