繁体   English   中英

如何修复 C 中的取消引用链表 NULL 指针

[英]How to fix dereferencing linked list NULL pointer in C

我目前在 function createDeck中创建链接列表时遇到问题。 它一直告诉我我的指针temp正在被取消引用。 我已经尝试在main中分配它,但它似乎没有做任何事情。 我在下面附上了我的代码示例。

typedef struct card_s {
    char suit[9];
    int value;
    struct card_s *next, *previous;
} card;

void createDeck(card *p, card **hl, card **hr, FILE *inp) {
    card *temp = (card *)malloc(sizeof(card));

    while (fscanf(inp, "%d %s", &temp->value, temp->suit) != EOF) {
         if (*hl == NULL) {  //beginning of list
             temp->next = NULL;
             temp->previous = NULL;
             *hl = temp;  // headp equals temp if null
             *hr = temp;
         } else
         if (p->next == NULL) {  //end of list
             p->next = temp;
             temp->previous = p;
             *hr = temp;
             temp->next = NULL;
         }
     }
}

void printDeck(card *head) {
    while (head != NULL) {
        printf("Value: %d Suit: %s", head->value, head->suit);
    }
}

int main(void) {
    FILE *inp;
    card *headl = NULL, *headr = NULL;

    inp = fopen("cards.txt", "r"); 
    if (inp == NULL) {
        printf("can't read file");
        return -1;
    }
    createDeck(headr, &headl, &headr, inp);
    printDeck(headl);
    return 0;
}

main中,您将headr (即 NULL)作为第一个参数 ( p ) 传递给createDeck 在例程中,您在代码到达else if (p->next == NULL)之前不会更改p ,此时p是 NULL ,因此您会收到NULL pointer reference错误。 也许您需要在if语句中添加一个分支以在else if (p->next == NULL) else if (p == NULL) NULL) 。

使用AddressSanitizer运行会发现问题。

AddressSanitizer:DEADLYSIGNAL
=================================================================
==80527==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000010 (pc 0x0001049c6e15 bp 0x7ffeeb239420 sp 0x7ffeeb2393f0 T0)
==80527==The signal is caused by a READ memory access.
==80527==Hint: address points to the zero page.
Provided dSYM: [/Users/schwern/tmp/test_c/./test.dSYM/Contents/Resources/DWARF/test] does not match symbol owner 0x7f9a2a61a380
    #0 0x1049c6e14 in createDeck test.c:20
    #1 0x1049c6f12 in main test.c:45
    #2 0x7fff5dfef3d4 in start (libdyld.dylib:x86_64+0x163d4)

第 20 行是else if (p->next == NULL) { p作为头文件传入,即headr p->next尝试取消引用 null 指针。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM