簡體   English   中英

鏈表-細分錯誤

[英]Linked List - Segmentation Fault

該代碼應構成用戶輸入的十個名稱的鏈接列表,並應打印出該列表。

#include<stdio.h>
#include<stdlib.h>
struct NameList
{
    char *name;
    struct NameList *nname;
};
typedef struct NameList NL;

int main()
{
    int i;
    NL *first;
    NL *next;
    first = (NL*)malloc(sizeof(NL));
    if (first ==NULL)
            printf("Memory not properly allocated\n");
    NL *pNames;
    pNames =  first;
    for(i = 0; i<10; i++)
    {
            printf("Enter a name: ");
            scanf("%s", &pNames->name);
            if(i == 9)
                    next = NULL;
            else
                    next = (NL*)malloc(sizeof(NL));
            pNames->nname = next;
            pNames = pNames->nname;
    }

到這里為止,沒有問題,我輸入了十個名稱,但是一旦輸入姓氏,就會出現分割錯誤。 我猜它起源於此,但我不確定

        pNames = first;
        while(pNames != NULL)
        {
                printf("%s\n", pNames->name);
                pNames = pNames->nname;
        }


    }

該行是源:

printf("Enter a name: ");
scanf("%s", &pNames->name);

最好創建一個像這樣的靜態緩沖區:

char buf[20];

然后

printf("Enter a name: ");
scanf("%s", buf);

最后:

pNames->name = strdup(buf);

編輯:為了完整起見,存在緩沖區溢出的風險。 其中超過某些字符的字符超過了緩沖區的末尾,從而導致未定義的行為。 @ebyrob所建議的那樣 ,可以通過這種方式緩解這種情況。

fgets(buf, 20, stdin);
allocate space for "name", preferably use std::string

    you need to get "next" node.

      for(i = 0; i<10; i++)
            {
                    printf("Enter a name: ");
                    scanf("%s", &pNames->name);
                    if(i == 9)
                            next = NULL;
                    else
                            next = (NL*)malloc(sizeof(NL));
                    pNames->nname = next;
                    pNames = next;
            }

              pNames = first;
                while(pNames != NULL)
                {
                        printf("%s\n", pNames->name);
                        pNames = pNames->next;
                }

您尚未分配內存來保存NameList對象的name字段。 name字段的類型為char * ,它有足夠的空間容納指針,而不是字符串。 當您執行scanf(%s, &pNames->name); 您告訴scanf將名稱寫入該內存位置,但這將覆蓋比存儲指針所需的字節更多的東西。

相反,您可以先將scanf加載到臨時數組中,然后malloc足夠的空間來容納它

char *tempbuff = malloc(128); // or some large enough buffer
for (i = 0; i<10; ++i) {
    // load the input into tempbuff first
    scanf("%s", tempbuff);
    // now make room for the string in the current object
    pNames->name = malloc(strlen(tempbuff)+1); // leave room for trailing null
    // now copy it from the tempbuff to its new home
    strcpy(pNames->name,tempbuff);
    .... // rest of code

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM