【问题标题】:Why does the program crash upon printing the two lastnames?为什么程序在打印两个姓氏时会崩溃?
【发布时间】:2015-04-12 00:51:56
【问题描述】:

似乎我的程序在打印两个姓氏时都崩溃了,我不明白为什么这个链接列表会在打印两个姓氏时崩溃。希望有任何帮助:((。我正在实现一个包含多个元素的链接列表,但是我只是打印了姓氏以查看列表是否会正确迭代,结果证明它在打印第二个姓氏“程序员”后崩溃。

struct user
{

     char email[30];
     char lastname[30];
     char firstname[30];
     char phonenumber[20]; 
     char status [50];
     char password [50];

};


struct nodeTag {
    struct user  data;
    struct nodeTag *pNext; 
    struct nodeTag *pPrev;
};

typedef struct nodeTag nodeStructType;


int main(){

    nodeStructType *pFirst;
    nodeStructType *pSecond;
    nodeStructType *pRun;

    pFirst = malloc(sizeof(nodeStructType));
    strcpy(pFirst->data.email,"art@yahoo.com");
    strcpy(pFirst->data.password,"artist");
    strcpy(pFirst->data.lastname,"iamaartist");
    strcpy(pFirst->data.firstname,"artist");
    strcpy(pFirst->data.status,"Hello i am a artist");
    strcpy(pFirst->data.phonenumber,"092712345678");
    pSecond= malloc(sizeof(nodeStructType));

    pFirst->pNext=pSecond;
    strcpy(pSecond->data.email,"programming@yahoo.com");
    strcpy(pSecond->data.password,"programmer");
    strcpy(pSecond->data.lastname,"programmer");
    strcpy(pSecond->data.firstname,"programmer");
    strcpy(pSecond->data.status,"Hello i am a programmer");
    strcpy(pSecond->data.phonenumber,"092712345678");


    pRun=pFirst;
    while(pRun->pNext!=NULL){
    printf("%s\n", pRun->data.lastname);
    pRun=pRun->pNext;
   }

}

【问题讨论】:

  • 分配pSecond后需要设置pSecond->pNext = NULL。否则,while 可能会在它不为零时尝试使用它。
  • 另外,nodeStructType 是什么?这不在您发布的代码中。
  • 这是一个 typedef 抱歉。

标签: c linked-list


【解决方案1】:

TL;DR:正如 lurker 上面评论的那样:您需要确保您的 pNext 指针明确指向链表末尾的 NULL

当您在 C 中从系统中 malloc() 内存时,它会尝试找到一个足够大的块来容纳您正在使用它的任何内容,但不会为您执行该内存的清理 - 您正在最后一个程序没有清理的垃圾。您看到的是没有触发 while 循环条件,因为位于 pSecond->pNext 的任何内容都不是指向 NULL (0x0) 的指针。

最重要的是,如果您重新启动系统并运行该程序几次,您可能会(不)走运并遇到一个场景 pSecond->pNext 实际上确实恰好指向 NULL, 确实导致了相当混乱的情况。

奖励:如果您希望函数调用为您处理初始化(为零)内存,请查看void *calloc(size_t num_elements, size_t element_size);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-01
    • 1970-01-01
    • 2020-11-21
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多