Tell me more ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

For example, a common error in C/C++ is to use the assignment operator = instead of the comparison operator ==.

share|improve this question
13  
By looking at the answers so far, it would appear that the most common mistake in coding is using languages from the C family in the first place. ;) – Mason Wheeler Sep 10 '10 at 22:30
1  
See also stackoverflow.com/questions/345737/… – pramodc84 Oct 4 '10 at 12:05
show 3 more comments

closed as not constructive by Aaronaught, Walter, user281377, Dori Jul 3 '11 at 3:05

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or specific expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, see the FAQ for guidance.

36 Answers

1 2
up vote 37 down vote accepted

Off-by-one errors

Iterating through a loop either once too often or one time less than intended, e.g.

for($i = 1; $i < $number_of_times_to_loop; $i++)

will go through a loop once less than intended. Changing the < to <= would get the above loop to cycle $number_of_times_to_loop as intended.

Another type of this error is the Fencepost error, so-called due to the following illustrative example:

Given a 100m stretch of land, how many fence posts do you need to dividie it in to 10 equal sections? Typical answer is 10 (100/10), forgetting the extra post needed for the outer boundary.

| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | <-- divisions

1---2---3---4---5---6---7---8---9---10---11 <-- posts required

share|improve this answer
show 6 more comments

Forgetting to close connections. (HTTP, database, whatever.)

Closing the connections prematurely.

share|improve this answer
2  
Of course, this one is kind of language specific. If you're using thing like RAII correctly in languages that have deterministic destruction, this becomes much less of a headache, because you never have to worry about closing things. – Billy ONeal Oct 6 '10 at 20:14
show 6 more comments

Writing

if (x > 5) return true;
else return false;

instead of

return (x > 5);
share|improve this answer
24  
If you have difficulty parsing return (x>5), you need a new job :P – Chinmay Kanchi Sep 2 '10 at 10:43
12  
This isn't really a "mistake" so much as a "sewer-grade bad code smell." That code will do what the writer thinks it's going to do. – BlairHippo Sep 2 '10 at 13:58
2  
I think that to the novice programmer, the first code snippet is much clearer. It is more readable that way, the other code needs explaination. – the_drow Oct 6 '10 at 9:31
3  
@JBRWilkinson: The longer version takes longer to read. – Gelatin Oct 6 '10 at 16:08
2  
Wow, anyone who disagrees with this answer is a complete idiot. Not afraid to come out and say it. – Jonathan Sterling Oct 7 '10 at 18:53
show 9 more comments

In C#, using throw ex instead of throw inside of a catch block. The former will reset the stack trace.

share|improve this answer
show 4 more comments

Misplaced semicolon C/C++ and/or alignment:

if(x == 5);  
  doSomething();  

doSomething() is always called even when x is not 5.

Obviously you know not to put a semicolon at the end of the if but sometimes it can be an overlooked typo.

share|improve this answer
3  
This is a serious problem in JavaScript, where semicolons are optional and are injected by the language parser - sometimes in places where they don't belong. – greyfade Sep 1 '10 at 21:20
2  
This is very common, and one of the reasons I avoid inline ifs in C style languages. I'd always enclose the call to doSomething() in braces. – Paddyslacker Sep 6 '10 at 15:30
3  
@Paddyslacker: if (x == 5); { doSomething(); }. Still the same problem. – configurator Oct 6 '10 at 9:37
show 5 more comments

Test using assignment = instead of comparison ==.

if( status = 10 ) {
    doSomething();
} else {
   doSomethingElse();
}

Mhh I wonder we never execute the else part

share|improve this answer
2  
Many modern languages will at least flag this as a warning, and some will outright refuse to compile it. But for the languages that let it slide without complaint, it's a nasty little bastard. – BlairHippo Sep 16 '10 at 14:09
2  
Having read McConnell (I think it was him), "back in the day", I always use "Yoda" notation. More force of habit now. I know this will trigger a debate, say what you want, before TDD, this saved me more than once. – DevSolo Oct 7 '10 at 18:59
2  
As I've said before K&R's choice to use = and == in this way COMBINED with the "assignment returns something" was a bad mistake. – Gerry Oct 8 '10 at 2:01
1  
In C# if requires a bool, which I find preferable. I like to give assignments their own line anyway. – Tim Goodman Nov 16 '10 at 15:36

Forgetting the ; is probably the most common mistake in C-family languages. Failing to check the bounds of an array is probably another very common mistake in languages that allow you to make it...

share|improve this answer
2  
Adding the ; was my mistake when starting VB.NET! – Moshe Sep 1 '10 at 20:36
19  
@Moshe: Starting with VB.NET was your mistake ;P – OscarRyz Sep 1 '10 at 21:30
1  
forget the braces, go the python way! :) – tsudot Sep 5 '10 at 10:21
show 3 more comments

Doing this in C/C++ :

#define VALUE 5;

It will cause compilation error elsewhere in your code.

share|improve this answer
6  
Worse than compilation errors: x = VALUE + 1; will compile, but quietly do the wrong thing. – Mike Seymour Oct 7 '10 at 13:04
show 1 more comment

Directly using variables without defining it in Javascript. Hence variables will have global scope. And programmer spends whole time debugging the scripts!!

share|improve this answer
2  
Not just Javascript -- this happens in most languages where variable declaration is optional. – Billy ONeal Oct 6 '10 at 20:16

I saw quite a few errors with missing break in switch statements (C++, Java). Fortunately C# forbid this practice.

switch (var) {
    case 1:
        //do something
    case 2:
        //do something else
}
share|improve this answer
1  
Where's your default: – PSU_Kardi Oct 6 '10 at 19:54
4  
@PSU: When there's no sensible default case, one should not be added. – Billy ONeal Oct 6 '10 at 20:15
1  
@Sjoerd: There are times when you just want to do nothing for non-explicitly-listed case values. Omitting the default is the correct approach there. – dan04 Feb 26 '11 at 19:52
show 2 more comments

I love the

a =+ 1;

believing that a will be incremented.

share|improve this answer
2  
That would have been correct in B – finnw Sep 2 '10 at 10:52
2  
And early versions of C. – Joe D Sep 17 '10 at 17:05

Recursive properties in C#:

private string foo;
public string Foo
{
   get { return Foo; }
}

Doesn't happen so often now we have auto-properties, but it's still something I wish the compiler would pick up on.

share|improve this answer
show 2 more comments

Character encoding

Working with Unicode: converting to/from/between ASCII/ISO 8859-1/Windows-1252/UTF-8 and other encodings, double encoding, not keeping track across applications, systems, protocols and file formats what encoding textual bytestrings are stored in... the list goes on. Few things are gotten wrong this often.

Very closely related: string escaping and unescaping, the bane of too many websites.

share|improve this answer
show 2 more comments

In languages like C#, changing the value of a parameter passed in to a method and then wondering why it's not updated in the calling code.

share|improve this answer

Forgetting to terminate a worker thread when a GUI app exits, so the process continues to run, out of sight.

share|improve this answer
show 3 more comments

Null References.

In OOP an object has control ( or should have control ) over the attributes/data of himself.

By setting them to an usable state and controlling how those attributes are modified, the source code prevents using null references ( Initialize with valid values ).

The common mistake is to allow the modification of these attributes with a potentially null reference.

Ej. in Java:

class Customer {
    private final String name; // null at this point 
    public Customer( String named ) {
        if( named == null ) { throw IllegalArgumentException("name cannot be null"); }
        this.name = named; // no longer null and the object has a valid state 
    }

    public String getName(){
        return this.name;// ok 
    }
    public void setName( String newName ) {
        this.name = newName; // eeerh... common programming error if newName = null 
    }
    public int someCalculation() {
        return this.name.length();// NullPointerException 
    }
}

A possible workaround is:

1.- Remove the setter

2.- Validate the setter

public void setName( String newName ) {
    if( newName == null ) { throw new NullPointerException("newName must be not null"); }
    this.name = newName;
}

That is, reject the invalid value, the let know the caller, they are using the object wrong. If the program is to fail, it is much better to fail fast.

One, mistake to try to mitigate this problem is to validate before each call:

public int someCalculation() {
    if( this.name != null ) {  
        return this.name.length();
    } else {
        return 0;
    }
 }

But, its too late, because at that point the object no longer trust its internal data, and that pattern if( x != null ){} will spread all over the place, just making things worst.

share|improve this answer
show 2 more comments

Catching exception that you don't know how to recover from, or catching a large family of exceptions (or even all exceptions) and not re-throwing when you encounter one that you don't know how to handle.

In .NET, not bothering to look up what exceptions can be thrown in the documentation (or even the intellisense tooltip) and allowing exceptions that you should have caught (and either recovered from or wrapped and thrown) be bubbled up and to a caller who neither expects them nor understands them.

share|improve this answer
1  
@configurator, @Billy: Both true, but only regarding the second paragraph. @configurator: Java only enforces that for checked exceptions, creating an odd dichotomy - should my exception be checked or unchecked? If you follow the advice of this article's bottom line, then you're left with the glaring question of how are you supposed to know if the user can recover from your exception? Only the user can know that, and he doesn't yet exist! – Allon Guralnek Oct 6 '10 at 23:10
2  
Also, I've seen Java's forced exception handling being abused many times. The developer doesn't know nor care how to handle all of the declared exceptions at this instant. All he wants is to be able to compile and see if his code works. He can't declare throws since that will cause the caller not to compile, so he puts an empty catch-all. It compiles, the code works, and time constraints dictate he moves forward, leaving the exception-hiding catch clause. – Allon Guralnek Oct 6 '10 at 23:11
show 7 more comments

One programming error I've seen a ridiculous number of times: Bad list management.
It usually looks like this:

private void TrimList( List<int> values, int garbageValue )
{
    for (int i = 0; i < values.Count; ++i)  
    {
        if (values[i] == garbageValue)
        {
            values.RemoveAt( i );
        }
    }
}

If you ever see this problem, you'll have to review the whole codebase. You're going to see flavours of this problem in multiple places.

share|improve this answer
show 3 more comments
  • Memory leak in C or C++. Using the RAII idiom in C++ is very helpful.
  • Another memory error is double free in C and C++, which can be disastrous as well.
share|improve this answer

When switching between PHP and C♯/Java, I often forgot and write ' instead of " for string constants and end up having compiling errors.

Like:

PHP

<?php
echo 'hello'; // allowed =)

C♯

Console.Write('hello world'); // <- error!
share|improve this answer
3  
we had a guy interview with us and called, "C pound" yeah, he didn't get the job. – Muad'Dib Sep 28 '10 at 5:57
2  
C-Hash... brown – mauris Oct 8 '10 at 4:34
show 4 more comments

In managed memory platforms: keeping a reference to an object for more time than it is needed causing memory to grow constantly and thinking that "the garbage collector doesn't work".

I have seen it many times while troubleshooting applications made by programmers new to .NET or Java.

Memory Leaks in Managed code

share|improve this answer

While taking 101, my teacher and I were combing through a student's program because it wouldn't compile. As it turns out, he used

''

instead of

"

everywhere in his program. Three hours of my life that I will never get back.

share|improve this answer
2  
For the next person looking quizzically at this answer, the top snippet has two single quote characters, the bottom snippet as one double quote character. – Frank Shearar Oct 2 '10 at 17:33
2  
Always use a mono-spaced font for code! – Sjoerd Feb 14 '11 at 0:47

Forgetting if string functions are 0-based or 1-based with whatever language I'm using

I'm always getting the wrong index when trying to parse a string using string functions because it's different for different languages. It almost always takes me more then one try to get it right.

For example...... I want a substring of a string starting at the index of X and ending at the index of Y... That's string.SubString(IndexOf('X'), string.IndexOf('Y') - string.IndexOf('X')) and I'm sure there's a +1 or -1 in one of those parameters somewhere....

share|improve this answer

I always write "pubic" instead of "public" in Java method signatures. Not really a functionality changing mistake, but a funny one all the same

share|improve this answer
1  
+1 In some early Fortran, you could write DAMNATION in place of DIMENSION. – Mike Dunlavey Nov 12 '11 at 17:02

A misplaced semicolon beside a while loop.

    while (i < max); // <-- infinite loop
    {
        // do something
        i++;
    }
    // why isn't the code below executing?
share|improve this answer
1  
This is why I use FOR almost all the time anymore -- it wraps all the loop maintenance logic in one localized place. – Billy ONeal Oct 6 '10 at 20:19
show 2 more comments

Thinking that just because it runs without an error that it is correct.

share|improve this answer

Assuming that default arguments in Python are not shared between function calls.

share|improve this answer

For example, a common error in C/C++ is to use the assignment operator = instead of the comparison operator ==.

And in OCaml language I'm currently using, it's common to use "physical equality operator" == instead of simple "equality operator" =. Ditto for "physical" != and "usual" <>. I'm already used to writing ==, but here I have to wrire =; this is a source of numerous errors.

"Physical equality" means "these two identifiers refer to the same object", contrary to "refer to (possibly different) equal objects". It has synnonyms in other languages as well.

share|improve this answer
show 3 more comments

Over reliance on refactoring tools, and code assistance tools (CodeRush / Resharper, etc).

Don't get me wrong, I love CodeRush, but they shouldn't be used solely to write the code.

In my mind a coder should be able to write code, and use them to assist where necessary.

share|improve this answer
show 1 more comment

Worst thing I ever saw was a fellow student who wrote something like this:

int main(){

    for(int x = 0; x < 10; x++){
        for(int y = x; y < 10; y++)
            cout << x + y << endl;
            for(int z = 0; z < y; z++){
               cout << x + y * z << endl;
            }
        }
    }

   return 0;
}

and was getting some weird weird errors.

See if you can spot the error...

share|improve this answer
1  
This could be an argument for putting your opening braces on their own line. Or for using Python. – Tim Goodman Sep 6 '10 at 19:02
3  
Errr.. this even compiles? – Billy ONeal Oct 6 '10 at 20:21
1  
Starting braces always go on their own line. Always. – Paul Nathan Oct 7 '10 at 19:32
show 5 more comments
1 2

Not the answer you're looking for? Browse other questions tagged or ask your own question.