-2

I am currently experiencing a problem with creating my linked list in my function createDeck. It keeps telling me that my pointer temp is being dereferenced. I have tried allocating it in main but it didn't seem to do anything. I've attached samples of my code below.

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;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
drewden
  • 1
  • 1

2 Answers2

1

In main you pass headr, which is NULL, as the first parameter (p) to createDeck. At no point in the routine do you change p before your code reaches else if (p->next == NULL), at which point p is NULL and thus you get a NULL pointer reference error. Perhaps you need to add a branch to your if statement to check for else if (p == NULL) prior to else if (p->next == NULL).

1

Running with an AddressSanitizer finds the problem.

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)

Line 20 is else if (p->next == NULL) {. p is passed in as headr which is null. p->next tries to dereference a null pointer.

Schwern
  • 153,029
  • 25
  • 195
  • 336