简体   繁体   中英

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;

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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