Very often, code is simply written as
while(ptr) ... since NULL corresponds to zero = false.
However – I have no personal objections to
clarity in code: if you want to add that "if p2 is not null," then by all means feel free.
FYI, usually I would write code like this ... like this:
Code:
while (ptr) { // or: while (ptr != NULL) ...
p2 = ptr->next;
free(ptr);
ptr = p2;
}
If you are inside the "while" loop, you know that
ptr isn't NULL because you are here.
But again, clarity: "it works," "you can prove it (by testing)," and "it is clear to the human reader." The compiler doesn't really care – it knows how to "optimize away" things anyway.
I explicitly set freed pointers to NULL, as I've said, specifically so that any
other code which encounters this pointer won't do the wrong thing. And, now I don't have to care where it might be. In any case, I don't have to "test for NULL" because
free() recognizes and ignores NULL.