Tuesday, September 1, 2015

A note on pushd and popd commands

Users of Linux shell are familiar with pushd & popd commands. But wait a minute, how does it work? How does it remember the directories which it traversed. Just a stack functionality right?
As you are aware, bash does fork+exec on the commands it runs and hence it is impossible for pushd & popd to store the directory list if spawned afresh. The solution is none other than the method used by bash for 'cd' command. Yes, the commands 'popd' & 'popd' too nestle within the bash executable ;). Of-course the concept of shared memory can pitch-in but why complicate when there is simpler solution ;)

The experiment as mentioned in my 'cd' post

heramba@heramba-MS-7640 ~ $ which pushd
heramba@heramba-MS-7640 ~ $ which ls
/bin/ls
heramba@heramba-MS-7640 ~ $ which popd

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?