Saturday, April 18, 2015

A NULL pointer trivia

Off-late, I have been pondering on the NULL checks in 'C'. As I skimmed through programming forums, one aspect that arose was the checking of NULLness of pointer.

For ex:

char *k = NULL;

if (!k)
{
}
else
{
}

What do you think? Will it ever fall through the else block? Some say, Yes! It is possible to have NULL as a pointer which is reserved for systemic purpose (not even kernel). So the ideal way would be

if (k == NULL)
{
    //bail out
}

Moving a step ahead, we nowadays have grandeur of VMAs which means expression "!k" is always comparing with VMA rather than physical address. However, NULL is constant expression defined by compilers rather than OS by itself which means first example may sometimes mislead.

So what do you say, the first one is not right way? May not be! The C standard says NULL is integer constant expression with a value zero, and resolving to generic pointer expression. This means the first block is always safe provided the compilers follow the standards. Also note that first is quite optimized version since assembly requires to check JNZ instruction while the other (k==NULL) requires copying the address to register and comparing!

What is your opinion?

No comments:

Post a Comment