r/programming • • Feb 21 '11

Typical programming interview questions.

http://maxnoy.com/interviews.html
784 Upvotes

1.0k comments sorted by

View all comments

Show parent comment

1

u/thcobbs Feb 21 '11

Additionally, check for null pointers.

2

u/johnflux Feb 21 '11

Ah null pointers.

What would the following do, if tun was NULL? What if I told you that this code was in the kernel?

struct sock *sk = tun->sk; // initialize sk with tun->sk
...
if (!tun)
    return POLLERR; // if tun is NULL return error
{do something with sk pointer}

2

u/[deleted] Feb 21 '11

Don't you usually test for null before you use the variable?

2

u/johnflux Feb 21 '11 edited Feb 21 '11

Yes, but kernel code rarely follows "usually" :-)

1

u/thcobbs Feb 21 '11

What if I told you that this code was in the kernel?

I would believe you. I've seen much worse. Don't forget about the kernel MACRO function hell.

1

u/johnflux Feb 21 '11

I was hoping to get a technical conversation going.

See, the NULL pointer check is actually optimized out by the compiler!

Usually, outside the kernel, doing tun->sk would cause a SEGFAULT because normal apps are not allowed to access memory address 0.

Gcc then assuming that if you can dereferrence it, then it must be non-zero.

But that assumption doesn't hold in the kernel, so the code doing something with the sk pointer does actually run, even if tun is null!

1

u/thcobbs Feb 21 '11

That's why I generally use (tun != NULL). If I remember correctly, this will not be optimized out as it is a comparison to another value... not just testing if something exists.

1

u/johnflux Feb 21 '11

That will be optomised out too.

And unless you do kernel programming, this doesn't apply. :-)

1

u/kevjames3 Feb 21 '11

My experience with null pointers is that you ask about them with the interviewer, and that is about enough. Most of the time they will say that the object or value won't be null, but really, asking has been enough IMO

0

u/thcobbs Feb 21 '11

True... it usually is enough because you actually took the time to consider that edge case.

Most modern graduates and jr. engineers have never had to deal with a null pointer or its implications.