簡體   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