簡體   English   中英

為什么在打印兩個姓氏時程序崩潰?

[英]Why does the program crash upon printing the two lastnames?

看來我的程序在打印兩個姓氏時崩潰了,我不知道為什么在打印兩個姓氏時此鏈表會崩潰的原因。 希望得到任何幫助:((.。我正在實現一個具有多個元素的鏈表,但是我只是打印了姓氏,以查看列表是否可以正確迭代,結果顯示它在打印第二個姓氏“程序員”后崩潰。

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

}

TL; DR:如上所述, pNext者:您需要確保pNext指針在鏈接列表的末尾顯式指向NULL

當您在C語言中從系統中分配malloc()內存時,它會嘗試找到一個足夠大的塊來容納您正在使用的內存,但不會為您執行對該內存的任何清理操作-您會得到垃圾最后一個程序沒有清理。 您看到的是while循環條件未觸發,因為pSecond->pNext內容都不是指向NULL(0x0)的指針。

最重要的是,如果重新啟動系統並運行幾次程序,可能會很不幸,並遇到pSecond->pNext實際上確實指向NULL的情況,從而導致相當混亂情況確實如此。

獎勵:如果您希望函數調用為您處理內存初始化(歸零),請查看void *calloc(size_t num_elements, size_t element_size);

暫無
暫無

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

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