Dan Garcia’s C puzzle answers

At least, my answers, that is…

A few days ago, I’ve published a quiz I’ve found on Dan Garcia’s class. The question was:

which snippets prints always 5?

1,,)
main() {
   int *a-ptr; *a-ptr = 5; printf(“%d”, *a-ptr);
}

2)

main() {
  int *p, a = 5;
  p = &a; …
  /* code; a & p NEVER on LHS of = */
  printf(“%d”, a);
}

3)

main() {
int *ptr;
ptr = (int *) malloc (sizeof(int));
*ptr = 5;
printf(“%d”, *ptr);
}

I guess we’ve got a language problem here 🙂 the *always* part is really important and I’d say is the key to getting things right.

Option 1 is completely wrong: even if the name of the pointer variable was correct, that still wouldn’t work because the pointer doesn’t point to a valid memory position.

Option 2 could work…but what would happen if you had something like this instead of the comments:

int* q = &a;
*q = 20;

I guess that we can dismiss this option as *always* printing 5, right?

Finally, option 3…it seems almost right, doesn’t it? In my opinion, it isn’t. why? Simply because it assumes that malloc won’t fail and that is not correct (btw, even though it wasn’t guaranteed of always printing 5, the code for option 3 is also incorrect: it’s missing a null check after the malloc call).

So, my answer is: none of them will always print 5!

This is not the answer Dan accepted. He says (and maybe he has a point) that he can’t think of any system which doesn’t have space for allocating an int. That’s why he considers option 3 to be the correct one. It might be a good argument, but I’m still saying that *always* is important here and that the most correct answer is none. Opinions?

Advertisements

~ by Luis Abreu on June 3, 2009.

2 Responses to “Dan Garcia’s C puzzle answers”

  1. Well… I agree with you. I have a saying… Assumptions are the mother of all …. wrong doings. 🙂

    Plus… I”m no c++ expert but shoudnt the app release the memory alocated? I bet that if you run this app on a infinite cicle will eventually go out of memory. But as I said I”m no c++ expert. In fact the last time I had to use C++ was many years ago 🙂 and I clearly recall not having a girlgrind then. 🙂

  2. Yep, it should…but it”s nor problematic here because it should get cleaned up when the process exits.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: