Jump to content

Common Programming Errors

WanderingFool

So I am writing this as a quick guide to help some people (and because I was a bit bored and needed something to do).  This will hopefully cover some of the more common issues that occur and their solutions...so if you have a problem that matches one of these problems then hopefully this can help fix it.

I have separated this into a few separate sections and if I make any errors someone please correct me, and feel free to contribute...I am trying to order in the most common occurances for each category.

Covered Topics (You can search for the expanded explanation by searching for the language followed by the title, e.g. Java -String- or Java -Input/Output Stream-)
General:
    Syntax errors:
        -Missing Semi-Colon-
            Most compilers will spot this error, but occastionally if you get multiple errors while compiling check for missing semi-colons (C/C++ coder read more full explanation)
    Wonky Numbers: (If you cannot find the answer in this category check for language specific categories, it might be in there)
        -Floating Points Inaccuracy- (Includes doubles)
            Many times the fault will be doing math using integers and forgetting to convert it to floating points before doing the math (1/3 = 0, 1/(float)3 = 0.333..., 1/3.0f = 0.3333...)

    Program Runs, but runs improperly:
        -If statement-
            Using = instead of ==
 
Java:
    Program Runs, but runs improperly:
        -String 1-
            Using == instead of equals()
    Quick notes:
        -Input/Output Stream-
            Saves using Big Endian

        -Bytes are signed-

            Apparently there is no unsigned byte type, so the range is -128 to 127
C/C++
    Program Runs, but runs improperly (or crashes):
        -Uninitialized Variables-
            int i; for(;i<10;i++) how many times will the loop run? It is undefined
        -Invalid Pointer-
            Invalid pointers can cause some wacky stuff
        -Buffer Overflow-
            Setting an array and not checking for when the input data exceeds the area you are writing to
    Program Runs perfectly in debug, but doesn't run in release version:
        -Uninitialized Variables-
            int i; for(;i<10;i++) how many times will the loop run? It is undefined
   Quick notes:

      -Comments in ANSI C-

            No full explanation, just noting that // is not valid in ANSI C (As I have seen this a few times at university)





Expanded Section:

General

General -Missing Semi-Colon-
    In C/C++ a missing ; might not always appear as an error on the correct line.  A good case of this is the following being done in a header

//Inside a headerstruct Point {    int x;} //Line 6

This actually won't give you an error at line 5, actually I find that it won't even give you an error in the header file.  Instead it will cascade the error down into the c code or other headers.  So while you are coding if you ever get a million errors when you are coding then try checking the headers (if you were editing them)
There might be cases where other compilers might not be good, for other languages, but from my experience Java is fairly good at spotting a missing ;

General -Floating Points Inaccuracy-
    A common issue is doing math in integer type without thinking about it.  While using integer math can be faster and have it's benefits if you need that decimal point be very careful that you are casting to floats before doing calculations.

void problemCode() {    int a = 1, b = 2, c = 3;    float value1,value2,value3,realValue;    value1 = a/b; //0    value2 = c/b; //1    value3 = 10.0f / c / b; //Depends how it is compiled, but in general this will produce the right number...but if the compiler decides to optimize it by doing (c/b) first then it will produce the wrong number    realValue = b / (float)c;}

General -If statement-
    This really doesn't need too much talking about.  Many times code that is submitted will look like so

...if(a=b) { //This will always be true when b != 0...

So make sure you put double equal signs ==, or if it is not a primitive type use .equals()

 

 

Java

Java -String 1-
    So this issue is quite a common one.  In other languages like C++ you can override ==, so when you compare two strings == works.  This is not the case for Java.  In java operators cannot be overriden, and == is defined as comparing two objects.  This is alright for 1 == 1, where Java is just comparing the memory, but for any object that is not a primitive type == will most likely not work.
Objects in Java contain references to other memory locations, so "Hi" and "Hi" might be contained two seperate places.  e.g. The first "Hi" might be at memory location 1234, while the second "Hi" at 1236, so Java is effectively comparing 1234 == 1236, when you compare "Hi" == "Hi". (This is a simplified example "Hi"=="Hi" actually might be true depending on how it was compiled...but that is not a good result)

To fix this use .equals(), all objects contain this. 

Java -Input/Output Stream-
    So I actually ran into this problem, so I decided to put this in here.  When you write to a file in Java, Java will save integers in BigEndian.  This is not really a problem, but if you are writing programs in multiple languages (e.g. C or C#) you need to be aware that if you are reading in data you need to convert either to Big Endian, or have java convert to Little Endian.  As another note (I could be wrong, but this is what I was taught years ago), C doesn't put a restriction on big or little endian, but is determined by the system so it might be better to ensure it reads/writes in Big Endian if you are writing a program that will be used with Java.
 

Java -Bytes are signed-

   So I came across this problem when counting colors based on bytes.  Java by default uses signed bytes, there is no unsigned byte primitive type.

 

There is no one true fix, you could use short or you could just adapt your code to handle -128 to 127

 

 

C/C++

C/C++ -Invalid Pointer-
    An invalid pointer can cause a crash, or create unexpected results (on occasion it can run as normal though).  In general this can happen when you create a pointer and forget to actually allocate enough memory for it; or you used free before you finished using a pointer

Fixes: When you call free(p); at the same time do p=0; This will ensure that if you use p again without using malloc you will cause a program crash (which is a lot easier to debug).
Pointers can be tricky, you need to be careful not to leave them hanging around after you finished using them

C/C++ -Uninitialized Variables-
    Consider the following

int i, sum;for(i=0; i<10; i++)    sum++;

This will equal 10, right?  WRONG.  This should equal 10, but there is no guarentee.   The problem is going int sum; will create space for sum, but it will not clear the memory.  This means sum could equal 0, 19, -200 before even the for loop.  Any variable you use should be initialized prior to using it.

I should note that depending on the program it might be able to run perfectly the first time, but if you keep using the program without restarting it, you could see this issue.  Or in the case of running the program in debug mode, sometimes the debug mode executable will actually have the variables zeroed out, which is why you should always test the release version as well.
Make sure to test programs multiple times as well (i.e. don't just call a function once, perhaps it takes a few goes to mess up the uninitialized variable).



C/C++ -Buffer Overflow-
    This is actually a very common bug in programs, with programmers not realizing there is an overflow until the program crashes or it is exploited.
In general every time you use an array of fixed size you should be checking when writing to it, that you do not exceed the length.  Consider this user input function

char storedName[100];void storeUserName(char* userName) {    strcpy(storedName, userName);}

This looks innocent enough, and in most cases it won't be a problem.  But if I were to put in 1000 characters then I am in trouble.  The storedName only has 100 bytes in memory, while 1000 characters will be written to memory.  Always make sure you check the bounds of your array before writing to it (especially if it is taking in input not generated by the program, e.g. from a user or a webpage).

Fix: Make sure to always check the length

#define MAXLENGTH 100;char storedName[MAXLENGTH];void storeUserName(char* userName) {    strncpy(storedName, userName, MAXLENGTH); //Notice it is now strncpy.  strncpy will make sure to check the length of the array so it won't copy too much    storedName[MAXLENGTH-1] = 0; //This is because strncpy might copy 100 characters, and char arrays need to end in 0}

Thanks to @rashdanml for reminding me about semi-colon
 
*Edit: Added Semi-colon's as rashdanml's suggestion
Added using integers when doing floating point math.

 

5/7/2014 - Added in a note about Java's use of signed bytes

-Added in a note about ANSI C

0b10111010 10101101 11110000 00001101

Link to comment
Share on other sites

Link to post
Share on other sites

This is going to help greatly for new programmers, 10/10 Nicely done.

Link to comment
Share on other sites

Link to post
Share on other sites

This should be pinned.

"If it has tits or tires, at some point you will have problems with it." -@vinyldash303

this is probably the only place i'll hang out anymore: http://linustechtips.com/main/topic/274320-the-long-awaited-car-thread/

 

Current Rig: Intel Core 2 Quad Q6600, Abit IN9-32MAX nForce 680i board, Galaxy GT610 1GB DDR3 gpu, Cooler Master Mystique 632S Full ATX case, 1 2TB Seagate Barracuda SATA and 1x200gb Maxtor SATA drives, 1 LG SATA DVD drive, Windows 10. All currently runs like shit :D 

Link to comment
Share on other sites

Link to post
Share on other sites

Almost every language:

missing semi-colon. 

Interested in Linux, SteamOS and Open-source applications? Go here

Gaming Rig - CPU: i5 3570k @ Stock | GPU: EVGA Geforce 560Ti 448 Core Classified Ultra | RAM: Mushkin Enhanced Blackline 8GB DDR3 1600 | SSD: Crucial M4 128GB | HDD: 3TB Seagate Barracuda, 1TB WD Caviar Black, 1TB Seagate Barracuda | Case: Antec Lanboy Air | KB: Corsair Vengeance K70 Cherry MX Blue | Mouse: Corsair Vengeance M95 | Headset: Steelseries Siberia V2

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

Very good! Thank you. I agree with the statement that it should be pinned.

Learning

Link to comment
Share on other sites

Link to post
Share on other sites

Scope errors

 

Using variables outside of their defined scope. These will produce a compiler error, and are generally easy to fix.

voidbar( void ){    if ( true )    {        int foo = 0;                ...    }    /* out of scope, compile time error */    printf( " %d ", foo );}

Local scope redeclaration. This is known as shadowing. Depending on the language, this can compile without error or warning making it difficult to track down, and lead to sneaky bugs.

 

This code is perfectly valid C, but may not be what you intended.

int foo;voidbar( void ){    int foo = 0;    printf( " bar: %d \n", foo );    {        int foo = 1;        printf( " bar block scope: %d \n", foo );    }}intmain(){    foo = 5;    bar();    printf( " main: %d \n", foo );    return 0;}

In GCC, use -Wshadow to get warnings when a local declaration shadows a global declaration.

main(i){for(;i<101;i++)printf("Fizz\n\0Fizzz\bBuzz\n\0%d\n"+(!(i%5)^!!(i%3)*3)*6,i);}

Link to comment
Share on other sites

Link to post
Share on other sites

the "=" vs "==" applies to c++ as well, it will work, but not the way you want it to:

int a = 1, b = 2;//-------------------------if(a == b) <- checks valueif(a = b) <- assigns value of b to a and evaluates to true

c++ header guards problems and when to use #include and when to use a class declaration instead.

#ifndef HEADERNAME_H#define HEADERNAME_H#include "Header.h" use only if using it's functionality in some way (like public enums)ORclass HeaderClass; otherwise use this to reduce the amount of stuff included,                   include it in cpp to use its functionality instead#endif //HEADERNAME_H 

in java there's the string .equals(string) vs ==, which are 2 different things.

String a = "asd", b = "asd"if(a == b) <- does not compare contents of the 2 stringsif(a.equals(b)) <- compares "asd" with "asd", evaluates to true if they are the same
Link to comment
Share on other sites

Link to post
Share on other sites

 

the "=" vs "==" applies to c++ as well, it will work, but not the way you want it to:

int a = 1, b = 2;//-------------------------if(a == b) <- checks valueif(a = b) <- assigns value of b to a and evaluates to true

c++ header guards problems and when to use #include and when to use a class declaration instead.

#ifndef HEADERNAME_H#define HEADERNAME_H#include "Header.h" use only if using it's functionality in some way (like public enums)ORclass HeaderClass; otherwise use this to reduce the amount of stuff included,                   include it in cpp to use its functionality instead#endif //HEADERNAME_H 

in java there's the string .equals(string) vs ==, which are 2 different things.

String a = "asd", b = "asd"if(a == b) <- does not compare contents of the 2 stringsif(a.equals(b)) <- compares "asd" with "asd", evaluates to true if they are the same

The == vs equals is already under the strings portion in java.  Although, I am moving that if to general as it was general problems.  I will consider the header guard thing...although I am not sure if it is a big problem...I really haven't seen any threads where that was an issue

0b10111010 10101101 11110000 00001101

Link to comment
Share on other sites

Link to post
Share on other sites

if(a = b) <- assigns value of b to a and evaluates to true

little correction: it does not evaluate to true

 

the assignment operator = stores the vaue of the right operand in the left operand, then returns the stored value, so

if(a = b)

is evalued just like

if(b)

in C and C++ the if statement evaluates to false if the argument is 0, evaluates to true otherwise

int a;int zero = 0, one = 1;if(a = zero) // evaluates false!!if(a = one) // evaluates true
Link to comment
Share on other sites

Link to post
Share on other sites

WHY ISN'T THIS PINNED YET??????

"If it has tits or tires, at some point you will have problems with it." -@vinyldash303

this is probably the only place i'll hang out anymore: http://linustechtips.com/main/topic/274320-the-long-awaited-car-thread/

 

Current Rig: Intel Core 2 Quad Q6600, Abit IN9-32MAX nForce 680i board, Galaxy GT610 1GB DDR3 gpu, Cooler Master Mystique 632S Full ATX case, 1 2TB Seagate Barracuda SATA and 1x200gb Maxtor SATA drives, 1 LG SATA DVD drive, Windows 10. All currently runs like shit :D 

Link to comment
Share on other sites

Link to post
Share on other sites

You can add this common error to the C section:

 

scanf("%d", num);

 

can any new programmers spot the error?  :P

------------------------------------

     ~ Live Love Code ~

------------------------------------

Link to comment
Share on other sites

Link to post
Share on other sites

Using scanf() is an error in and of itself  :)

main(i){for(;i<101;i++)printf("Fizz\n\0Fizzz\bBuzz\n\0%d\n"+(!(i%5)^!!(i%3)*3)*6,i);}

Link to comment
Share on other sites

Link to post
Share on other sites

Using scanf() is an error in and of itself  :)

Not that >_< lol but true. It works once you know how to use it properly.

The cons that you can't get away from is the overhead and sometimes stuff gets left in the buffer.

------------------------------------

     ~ Live Love Code ~

------------------------------------

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×