user2888425
user2888425

Reputation: 25

Why does NULL Pointer check not work while iterating through singly-linked list in C?

I'm trying to print from heap. If I come across a NULL pointer I should print NULL; otherwise, print it's value.

Sample output:

1   [2]
2   null
3   null
4   [7, 3]
5   null
6   [7]

But my code keeps crashing for dereferencing a NULL pointer.

Here is the code that I wrote to test:

void printResult(IntList* intL, int nNode, int nEdge)
{
    int i;
    for (i; i <= 10; i++)
    {
        if (intRest((intL))
        {
            printf("%d", intFirst((intL)[i]));
            intRest((intL)[i]);
        }
        else
            printf(" NULL ");
    }
}

//Here is the definition of functions:
//First
int intFirst(IntList oldL)
{
    return oldL->element;
}

/** rest
 */
IntList intRest(IntList oldL)
{
    return oldL->next;
}
//=================
struct IntListNode
{
    int element;
    IntList next;
};

//===================
typedef struct IntListNode * IntList;

Upvotes: 0

Views: 274

Answers (2)

LihO
LihO

Reputation: 42093

You have singly linked list consisting of nodes that are not stored in a continuous block of memory (they are rather scattered), thus trying to iterate through its elements this way:

for (i; i <= 10; i++)
    printf("%d", intFirst((intL)[i]));

results in undefined behavior since you are accessing the wrong memory. You should do something like:

struct IntListNode * ptr = *intL;
while (ptr) {
    printf("%d", ptr->element);
    ptr = ptr->next;
}

Upvotes: 8

Stefan
Stefan

Reputation: 17658

If

IntList intRest(IntList oldL)
{
    return oldL->next;
}

is your test for NULL in if (intRest((intL)),

then your code will crash if intL == NULL.

Upvotes: 4

Related Questions