jump to navigation

The Worst C Example Ever May 21, 2007

Posted by Imran Ghory in Software development.
37 comments

The Example:

strcpy(str, getpass("Enter password: "));

The first time I saw this I was shocked at how many problems this tiny example of code has (there’s a list of problems further on – if you want to try and figure out the problems yourself try to write a working getpass() function based upon this caller).

To put this example in context it came from Question 6.5 of the comp.lang.c FAQ in which this example is given as an example for how to achieve what the following piece of code is trying to do:

extern char *getpass();
char str[10];
str = getpass("Enter password: ");

For those of you who aren’t C programmers the above chunk of code won’t work as getpass() is returning a pointer to an array (in C strings are represented as arrays of chars) and C doens’t support implicit array copying.

However the “fixed” example is almost as bad as the original, only made marginally better by the fact it technically works. However it is horrendous as an example of good coding practice.

So what’s wrong with it ?

The newbie programmer has almost certainly implemented getpass() using the following method:

char* getpass(void)
{
char password[10];
scanf("%s\n", password);
return password;
}

This reads the password into a local variable which it then returns a pointer to it. The worst thing about this is the code will actually work sometimes and not other times leaving the programmer in a terrible confusion (local variables are allocated on the stack hence will get overwritten after the function ends).

A more spohisticated way to write this function and how it would be generally be done would be to use dynamically allocated memory as in the following:

char* getpass(void)
{
char* password = (char*) malloc(10);
scanf("%9s\n", password);
return password;
}

However in the original bad example the code is throwing away the pointer which getpass() returns, which means that it’s not possible to free that memory. Hence you end up with a memory leak, not good. So this solution is not good in the context.

The best possible getpass() you could get away with is to declare a static char array variable which you return a pointer to

char* getpass(void)
{
static char password[10];
scanf("%9s\n", password);
return password;
}

However this makes the function non-thread-safe and non-renterant which limits its use, and as well as that you end up storing the password in memory for the permanent life of the program.

So as you can see it’s impossible for even a good programmer to write a good getpass() function that can be called by strcpy(str, getpass(“Enter password: “)) , let alone the beginners that this document is targeted at.

A bonus bug

Plus for bonus points, there’s yet another sutble bug in this code. It uses strcpy() in an unsafe manner. Even professional developers often slip up when using strcpy, generally professionals always want to use strlcpy as strcpy is almost never used correctly. The reason it’s bad is the following scenario, imagine getpass() was changed to be the following:

char* getpass(void)
{
static char password[100];
scanf("%99s\n", password);
return password;
}

What makes it unsafe is that strcpy doesn’t know how many characters to copy, hence it just keeps copying from the source to the destination until it runs out of characters. Now that getpass() returns more than ten characters what happens ? – if you’re lucky the program will crash – if you’re unlucky the person typing in the password can take over the program and bypass the password protection.

So What ?

Well hopefully the above has convinced you that if you’re writing for beginners you should try to write examples that not only work, but also show good development practices. Especially online where space isn’t as major a consideration as it is in books.

Advertisements

How to pick a good Computer Science degree May 16, 2007

Posted by Imran Ghory in Computer Science, Software development.
11 comments

I recently came across a scathing article by a former Computer Science professor from the University of Leeds attacking his former department for “dumbing down” their curriculum. In the discussion on reddit that followed the question was raised about which universities still have good compsci departments.

I’d thought I’d try to answer that indirectly by coming up with a set of criteria any prospective student could use to judge for themselves how good an undergraduate compsci course is.

So without further ado the criteria:

  • How difficult are the modules/subjects offered ? – do they include math heavy topics such as cryptography, complexity, quantum computing, speech processing, etc. Do they include theoretical topics such as information and concurrency theory. Are the programming courses in depth, do they cover functional programming and language engineering or are they just “what is a loop” lectures.
  • Are there specialist units/subjects taught by researchers in that area ? – If a uni is teaching unique courses that are only available at a handful of universities around the world due to the specialisms then that’s probably a good sign. It means lecturers are driving the curriculum and you’re likely to have lecturers who are genuinely passionate about what they teach.
  • What’re the average entry grades for students ? – this matters for a number of reasons, not least because having intelligent motivated students means that lecturers won’t have to dumb down their material. Lecturers have to make sure they’re teaching at a level right for their students. If you’re an A* pupil in a class of D students then you’re going to feel unchallenged as the work will be aimed at a level far below you.
  • Who recruits at the university ? – Large tech companies tend to have a very good idea which universities are producing the best compsci graduates based upon the quality of those graduates they’ve hired. So look at a university’s website and see what companies regularly recruit there. Most big technology firms, investment banks, consultancies, etc. have campus calenders on their websites showing where they recruit.
  • What do students do for final year projects ? – if the majority are doing “e-commerce websites” then it’s probably time to run away. If the majority are doing “hard-core” innovative and interesting computer science projects across a range of areas then it’s probably a good sign.

Does anyone have any other suggestions for good criteria – can we establish the equivalent of The Joel Test for universities ?

Programming Knowledge versus Programming Ability May 16, 2007

Posted by Imran Ghory in Uncategorized.
54 comments

For some reason the single most common type of question on “programming language” exams seems to be of the form:

Which of the following are invalid variable names in Java?

  1. $char
  2. 1MyNumber
  3. case
  4. _int

(paraphrased from SCJP Exam for J2SE)

Imagine what a similar question might be in a football test:

Which of the following would result in a direct free kick to the opposing team ?

  • attempts to kick an opponent
  • attempts to trip an opponent
  • attempts to jump at an opponent
  • attempts to spit at an opponent

(paraphrased from the FIFA rules)

While it might be slightly useful for someone playing football to be able to answer the above correctly, the entire concept of trying to measure someone’s ability by measuring their knowledge is fundamentally flawed.

And that’s the fundamental problem with question posed above, as well as with programming exams in general.

There seems to be a popular misconception that if a software developer knows a lot about programming then it follows that they’re a good developer.

Returning to the football analogy imagine you were back at school picking players for your team. Who gets picked first:

  1. The kids who are athletic and good at football
  2. The kids who are athletic and can make a good run down the pitch, even if they’re football specific skills aren’t that great.
  3. The kids who aren’t athletic but know how to play football
  4. The kids who aren’t athletic and know nothing about football

If you had to pick a team now, made out of players you didn’t know anything about. how would you pick – would you give them all an exam about football rules and theory or would you have them run around the pitch kicking a ball ?

Hopefully most people will pick the second option and end up with a team that can actually play football well. However in the software profession there seems to be a sizable contingent of developers who hold the view that if someone knows a lot about programming then they’re a good programmer.

But it’s not just the pro-certification lobby who think like this, to take another example from a blog I read last month:

I don’t do well in programming tasks during interviews, and I’ve love someone to come into my comments and tell me I can’t program based on this event. No, I’ve only faked it while working for Nike, Intel, Boeing, John Hancock, Lawrence Livermore, and through 14 or so books–not to mention 6 years of online tech weblogging.

(from here, apologies to Shelley Powers for picking on her blog, but it’s one of the more eloquent blog posts on this topic that stuck in my mind, hence me quoting it).

Note that everything in that paragraph was about knowledge rather than ability. I’ve seen the CV’s of some vastly incompetent programmers who I’ve known and they’ve had phrases on their CV along the lines of “was involved in project X at big company Y”, when in actuality they were relegated to writing test scripts. Yet they could perfectly well talk about the project, what the development steps were, what the problems encountered were, how the team solved them, etc. These are all knowledge questions, not ability questions.

Similarly writing a book speaks about your knowledge of a language, not your ability as a programmer. Consider the following quote, would you want to work with this developer on a C++ project:

I have not written production software in over 20 years, and I have never written production software in C++. Nope, not ever. Furthermore, I’ve never even tried to write production software in C++, so not only am I not a real C++ developer, I’m not even a wannabe.

If you hadn’t already guessed – that quote is from Scott Meyers (one of the worlds most respected C++ authors). Not that I doubt Scott’s programming ability; but hopefully it does show that knowledge doesn’t necessarily mean experience.

So next time you’re trying to work out if someone’s a superstar coder, pause for a moment and make sure you’re considering both their programming knowledge and their programming ability, and not letting one substitute for the other.