链表 - 分段错误

时间:2015-10-21 20:01:35

标签: c linked-list

此代码应该生成由用户输入的十个名称的链接列表 它应该打印出该列表。

#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;
        }


    }

3 个答案:

答案 0 :(得分:2)

这一行是来源:

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);

答案 1 :(得分:0)

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;
                }

答案 2 :(得分:0)

您尚未分配内存来保存NameList个对象的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 加载足够的空间来保存它

@numbers = @client.available_phone_numbers.get('US').local.list(
   near_lat_long: '40.6928,-73.9903',
   distance: '5'
)