Error while programming

Encountering bugs is a huge part of the development process. Some of the best developers are those who have become comfortable with navigating the types of errors in programming and fixing them quickly.

The late computer scientist Edsger W. Dijkstra said, “if debugging is the process of removing bugs, then programming must be the process of putting them in.”

Experiencing different types of errors in programming is a huge part of the development process. The best developers become comfortable navigating the bugs they create and quickly fixing them.

Today, we’re going to talk about the seven most common types of programming errors and how you can avoid them.

1. Syntax Errors

Just like human languages, computer languages have grammar rules. But while humans are able to communicate with less-than-perfect grammar, computers can’t ignore mistakes, i.e. syntax errors.

For example, let’s say the correct syntax for printing something is print('hello'), and we accidentally forget one of the parentheses while coding. A syntax error will happen, and this will stop the program from running.

As your proficiency with programming language increases, you will make syntax errors less frequently. The easiest way to prevent them from causing you problems is to be aware of them early. Many text editors or IDEs will come with the ability to warn you about syntax errors at the time of writing.

Pro Tip: Code faster with TextExpander

TextExpander makes it easy to save commonly-used code snippets, documentation comments, and more — then insert them anywhere you type with a simple shortcut or inline search.

Click here to learn more.

2. Logic Errors

Logic errors can be the hardest to track down. Everything looks like it is working; you have just programmed the computer to do the wrong thing. Technically the program is correct, but the results won’t be what you expected.

If you didn’t check the requirements beforehand and wrote code to return the oldest user in your system when you needed the newest, you would have a logic error.

A famous example happened in 1999 when NASA lost a spacecraft due to miscalculations between English and American units. The software was coded one way but needed to work another.

When writing your tests, show them to the product manager or product owner to confirm that the logic you’re about to write is correct. In the example above, someone closer to the business would have spotted that you aren’t mentioning the fact it is the newest user that is required.

3. Compilation Errors

Some programming languages require a compilation step. Compilation is where your high-level language converts into a lower-level language that the computer can understand better. A compilation or compile-time error happens when the compiler doesn’t know how to turn your code into the lower-level code.

In our syntax error example, if we were compiling print('hello', the compiler would stop and tell us it doesn’t know how to convert this into a lower-level language because it expected a ) after the '.

If there is a compile-time error in your software, you won’t be able to get it tested or launched.

Like syntax errors, you will get better at avoiding these with time, but in general, the best thing you can do is get early feedback when it happens.

Compilation happens across all files of your project at the same time. If you’ve made lots of changes and see lots of compiler warnings or errors, it can be very daunting. By running the compiler often, you will get the feedback you need sooner, and you will more easily know where to address the issues.

4. Runtime Errors

Runtime errors happen as a user is executing your program. The code might work correctly on your machine, but on the webserver, there might be a different configuration, or it might be interacted with in a way that could cause a runtime error.

If your system took the input from a form and tried to capitalize the first letter of a name by doing something like params[:first_name].capitalize, this would break if the form was sent without a first name.

Runtime errors are particularly annoying because they directly impact your end user. A lot of these other errors will happen when you’re at your computer working on the code. These errors occur when the system is running and can stop someone from doing what they need to do.

Make sure you have good error reporting in place to capture any runtime errors and automatically open up new bugs in your ticketing system. Try and learn from each bug report so that in future you can guard against this type of error.

Making use of frameworks and community maintained code is an excellent way of minimizing these types of errors because the code is in many different projects, so it will have already encountered and fixed many issues.

5. Arithmetic Errors

An arithmetic error is a type of logic error but involves mathematics. A typical example when performing a division equation is that you cannot divide by zero without causing an issue. Very few people would write 5 / 0, but you might not think that the size of something in your system might sometimes be zero, which would lead to this type of error.

ages.max / ages.min could return an error if either ages.max or ages.min were zero.

Arithmetic errors can generate logic errors as we’ve discussed, or even run-time errors in the case of divide by zero.

Having functional tests that always include edge-cases like zero, or negative numbers is an excellent way to stop these arithmetic errors in their tracks.

6. Resource Errors

The computer that your program is on will allocate a fixed amount of resources to the running of it. If something in your code forces the computer to try and allocate more resources than it has, it can create a resource error.

If you accidentally wrote a loop that your code could never exit from, you would eventually run out of resources. In this example, the while loop will keep on adding new elements to an array. Eventually, you will run out of memory.

 while(true)
   my_array << 'new array element'
 end 

Resource errors can be hard to chase down because the machine you’re developing on can often be higher quality than the servers running your code. It is also hard to mimic real-world use from your local computer.

Having good reporting on resource usage on your web servers will flag code that is consuming too much of any type of resource over time.

Resource errors are an example of a type of error in programming that might be something for the operations team to fix rather than developers.

There are lots of load-testing applications and services that you can use to test what happens when multiple people try and run your code at once. Then, you can tune the testing to suit what is realistic for your application.

7. Interface Errors

Interface errors occur when there is a disconnect between how you meant your program to be used and how it is actually used. Most things in software follow standards. If input your program receives doesn’t conform to the standards, you might get an interface error.

For example, an interface error might happen if you have an API that requires that specific parameters are set and those parameters are not set.

Unless handled correctly, interface errors will look like an error on your side when it is an error on the caller’s side. This can lead to frustration from both sides.

Having clear documentation and catching these errors to pass back to the caller in a useful way is the best way of saying, “Hey, you haven’t given us what we need to process this request.” This will help keep support costs down and keep your clients happy because they know what they need to fix.

If you don’t catch these errors and pass them back to the caller, they will end up appearing like runtime errors in your reporting, and you will end up guarding against things excessively.

Errors Are Inevitable

We are, thankfully, decades past needing to have perfectly placed punch-cards appropriately done the first time. Software engineering is hard, requirements are often fuzzy, and the code changes often. Try not to beat yourself up and know that we all make mistakes.

Programming errors are inevitable. Get better at spotting them early, but know you will never be perfect.

Hopefully, this guide has prepared you for the different types of errors in programming and made sense of some of the most common error messages for you.

If you’ve been writing code for a long time, please comment below with some errors you’ve made recently, to help serve as reassurance for people who haven’t been writing code as long!

Programming errors are flaws in how applications work. They are commonly referred to as «bugs», hence the term “debugging”.

As a developer, you’ll find yourself spending a lot of time fixing bugs. A number of the errors you will meet are common, and knowing them will help you prevent them in the first place.

Here’s what you need to know on these three types of programming errors and how you can safeguard against them:

1. Runtime or Execution Errors

These are errors that occur when a program is executing (i.e. at runtime). They may cause a program to not execute properly or even not run at all.

Fatal runtime errors cause program execution to stop while the non-fatal ones cause execution to finish, but with incorrect results.

A typical runtime error is a division by zero error. Division by zero is supposed to yield an infinite result, but unfortunately, we haven’t come up with a data structure that can store that amount of data yet.

Therefore, division by zero leads to an arithmetic exception in the Java compiler.

2. Logic Errors

Logic errors are caused due to flawed reasoning. It’s important to note that these errors are not necessarily due to a “mistake” you’ve made. They may occur because you didn’t consider a certain execution scenario.

They are the most difficult to handle. This is because code with a logic error is a valid program in the language it’s written in. Therefore, it won’t throw a compiler error. The only issue is that it produces incorrect results.

A fatal logic error will cause program execution to stop while a nonfatal one will allow program execution to continue but with incorrect results.

A common logic error is an off-by-one error. This normally occurs when stating a loop-continuation condition. Say you want to print out the first five square numbers.

You might end up writing the code below in your for loop, which gives only the first four such numbers.

 for( int x=1; x<5; x++){ System.out.ln(x*x); } 

To avoid such an error, you could instead use the <= sign. Using the less-than-or-equal-to sign is more intuitive and you’ll therefore be less likely to mix up your relational operations.

Another common logic error is leaving out both braces of a control statement and yet the body below forms a block of code that is under its control.

Look at the example below. It checks if a random number is odd or even, then prints an output.

 import java.util.Random;

public class OddEven{
public static void main(String[] args) {
Random numberGenerator = new Random();
int randomNumber = numberGenerator.nextInt(10);

if ((randomNumber%2)==0)
System.out.println("Here is your lucky number :" + randomNumber);
System.out.println("The number "+ randomNumber +" that you got is even"); // line 11
}
}

Notice Line 11. It’ll always execute regardless of whether the random number you got is even. This would of course be logically wrong when the number you got is odd.

Including both System.out.println statements between braces { }, would have avoided this.

Another logic error to look out for is not providing a loop termination condition. This will result in an infinite loop and your program will never finish execution.

3. Syntax or Compile-Time Errors

These are errors caused due to violations of Java’s language rules. They’re also called compilation or compile-time errors.

These are the easiest errors to handle because your compiler will always report them. Many compilers even go ahead and tell you the line in your code the error is on.

Fault Tolerance

A practical way of dealing with software issues is to emlpoy fault tolerance by including exception handling. You can use try..catch statements to achieve this.

To continue with program execution regardless of the exception caught in the catch block, use the finally statement.

The syntax is:

 try{ // Block to execute if there are no issues } 
catch (Exception e){
// Block to handle issues found
}finally{ // Block to execute after catch
}

See the code example below:

 import java.util.Random;

public class RandomNumbers{
public static void main(String[] args) {
Random numberGenerator = new Random();

try{
for (int counter = 10; counter<=100; counter++){
int randomNumber = numberGenerator.nextInt(10);
System.out.println(counter/randomNumber); } }
catch(Exception e){
System.out.println("Division by zero encountered!");
}
finally{
System.out.println("Infinite value got");}
}
}

The above program generates a random number between zero and 10, and then uses that number to divide a counter value between 10 and 100. If division by zero is encountered, the system catches the error and displays a message.

Get Better at Coding

It’s good practice to add comments to your code. This will help you easily comb through your files when you have a bug. One small, but very important step to developing strong coding practices.

With good coding practices, you should be able to avoid common programming mistakes.

Types of Errors in C

Overview

An error in the C language is an issue that arises in a program, making the program not work in the way it was supposed to work or may stop it from compiling as well.
If an error appears in a program, the program can do one of the following three things: the code will not compile, the program will stop working during execution, or the program will generate garbage values or incorrect output. There are five different types of errors in C Programming like Syntax Error, Run Time Error, Logical Error, Semantic Error, and Linker Error.

Scope

  • This article explains errors and their types in C Programming Language.
  • This article covers the explanation and examples for each type of error in C Programming Language (syntax error, run time error, logical error, semantic error, linker error).

Introduction

Let us say you want to create a program that prints today’s date. But instead of writing printf in the code, you wrote print. Because of this, our program will generate an error as the compiler would not understand what the word print means. Hence, today’s date will not print. This is what we call an error. An error is a fault or problem in a program that leads to abnormal behavior of the program. In other words, an error is a situation in which the program does something which it was not supposed to do. This includes producing incorrect or unexpected output, stopping a program that was running, or hindering the code’s compilation. Therefore it is important to remove all errors from our code, this is known as debugging.

How to Read an Error in C?

In order to resolve an error, we must figure out how and why did the error occur. Whenever we encounter an error in our code, the compiler stops the code compilation if it is a syntax error or it either stops the program’s execution or generates a garbage value if it is a run time error.

Syntax errors are easy to figure out because the compiler highlights the line of code that caused the error. Generally, we can find the error’s root cause on the highlighted line or above the highlighted line.

For example:

#include <stdio.h>
int main() {
    int var = 10
    return 0;
}

Output:

error: expected ',' or ';' before 'return'
      4 |  return 0;

As we can see, the compiler shows an error on line 4 of the code. So, in order to figure out the problem, we will go through line 4 and a few lines above it. Once we do that, we can quickly determine that we are missing a semi-colon (;) in line 4. The compiler also suggested the same thing.

Other than the syntax errors, run time errors are often encountered while coding. These errors are the ones that occur while the code is being executed.

Let us now see an example of a run time error:

#include<stdio.h>

void main() {
    
    int var;
    var = 20 / 0;
    
    printf("%d", var);
}

Output:

warning: division by zero [-Wdiv-by-zero]
    6 |     var = 20 / 0;

As we can see, the compiler generated a warning at line 6 because we are dividing a number by zero.

Sometimes, the compiler does not throw a run time error. Instead, it returns a garbage value. In situations like these, we have to figure out why did we get an incorrect output by comparing the output with the expected output. In other cases, the compiler does not display any error at all. The program execution just ends abruptly in cases like these.

Let us take another example to understand this kind of run time error:

#include <stdio.h>
#include <stdlib.h>

int main() {
    
	int arr[1]; 
	arr[0] = 10; 

	int val = arr[10000]; 
	printf("%d", val); 
    return 0;
}

Output:


In the above code, we are trying to access the 10000th element but the size of array is only 1 therefore there is no space allocated to the 10000th element, this is known as segmentation fault.

Types of Errors in C

There are five different types of errors in C.

  1. Syntax Error
  2. Run Time Error
  3. Logical Error
  4. Semantic Error
  5. Linker Error

1. Syntax Error

Syntax errors occur when a programmer makes mistakes in typing the code’s syntax correctly or makes typos. In other words, syntax errors occur when a programmer does not follow the set of rules defined for the syntax of C language.

Syntax errors are sometimes also called compilation errors because they are always detected by the compiler. Generally, these errors can be easily identified and rectified by programmers.

The most commonly occurring syntax errors in C language are:

  • Missing semi-colon (;)
  • Missing parenthesis ({})
  • Assigning value to a variable without declaring it

Let us take an example to understand syntax errors:

#include <stdio.h>

void main() {
    var = 5;    // we did not declare the data type of variable
     
    printf("The variable is: %d", var);
}

Output:

error: 'var' undeclared (first use in this function)

If the user assigns any value to a variable without defining the data type of the variable, the compiler throws a syntax error.

Let’s see another example:

#include <stdio.h>

void main() {
    
    for (int i = 0;) {  // incorrect syntax of the for loop 
        printf("Scaler Academy");
    }
}

Output:

error: expected expression before ')' token

A for loop needs 3 arguments to run. Since we entered only one argument, the compiler threw a syntax error.

2. Runtime Error

Errors that occur during the execution (or running) of a program are called RunTime Errors. These errors occur after the program has been compiled successfully. When a program is running, and it is not able to perform any particular operation, it means that we have encountered a run time error. For example, while a certain program is running, if it encounters the square root of -1 in the code, the program will not be able to generate an output because calculating the square root of -1 is not possible. Hence, the program will produce an error.

Runtime errors can be a little tricky to identify because the compiler can not detect these errors. They can only be identified once the program is running. Some of the most common run time errors are: number not divisible by zero, array index out of bounds, string index out of bounds, etc.

Runtime errors can occur because of various reasons. Some of the reasons are:

  1. Mistakes in the Code: Let us say during the execution of a while loop, the programmer forgets to enter a break statement. This will lead the program to run infinite times, hence resulting in a run time error.
  2. Memory Leaks: If a programmer creates an array in the heap but forgets to delete the array’s data, the program might start leaking memory, resulting in a run time error.
  3. Mathematically Incorrect Operations: Dividing a number by zero, or calculating the square root of -1 will also result in a run time error.
  4. Undefined Variables: If a programmer forgets to define a variable in the code, the program will generate a run time error.

Example 1:

// A program that calculates the square root of integers
#include <stdio.h>
#include <math.h>

int main() {
    for (int i = 4; i >= -2; i--)     {
        printf("%f", sqrt(i));
        printf("n");
    }      
    return 0;
}

Output:

2.000000
1.732051
1.414214
1.000000
0.000000
-1.#IND00
-1.#IND00

**In some compilers, you may also see this output: **

2.000000
1.732051
1.414214
1.000000
0.000000
-nan
-nan

In the above example, we used a for loop to calculate the square root of six integers. But because we also tried calculating the square root of two negative numbers, the program generated two errors (the IND written above stands for «Indeterminate»). These errors are the run time errors.
-nan is similar to IND.

Example 2:

#include<stdio.h>
 
void main() {
    int var = 2147483649;

    printf("%d", var);
}

Output:


This is an integer overflow error. The maximum value an integer can hold in C is 2147483647. Since in the above example, we assigned 2147483649 to the variable var, the variable overflows, and we get -2147483647 as the output (because of the circular property).

3. Logical Error

Sometimes, we do not get the output we expected after the compilation and execution of a program. Even though the code seems error free, the output generated is different from the expected one. These types of errors are called Logical Errors. Logical errors are those errors in which we think that our code is correct, the code compiles without any error and gives no error while it is running, but the output we get is different from the output we expected.

In 1999, NASA lost a spacecraft due to a logical error. This happened because of some miscalculations between the English and the American Units. The software was coded to work for one system but was used with the other.

For Example:

#include <stdio.h>

void main() {
    float a = 10;
    float b = 5;
    
    if (b = 0) {  // we wrote = instead of ==
        printf("Division by zero is not possible");
    } else {
        printf("The output is: %f", a/b);
    }
}

Output:


INF signifies a division by zero error. In the above example, at line 8, we wanted to check whether the variable b was equal to zero. But instead of using the equal to comparison operator (==), we use the assignment operator (=). Because of this, the if statement became false and the value of b became 0. Finally, the else clause got executed.

4. Semantic Error

Errors that occur because the compiler is unable to understand the written code are called Semantic Errors. A semantic error will be generated if the code makes no sense to the compiler, even though it is syntactically correct. It is like using the wrong word in the wrong place in the English language. For example, adding a string to an integer will generate a semantic error.

Semantic errors are different from syntax errors, as syntax errors signify that the structure of a program is incorrect without considering its meaning. On the other hand, semantic errors signify the incorrect implementation of a program by considering the meaning of the program.

The most commonly occurring semantic errors are: use of un-initialized variables, type compatibility, and array index out of bounds.

Example 1:

#include <stdio.h>

void main() {
    int a, b, c;
    
    a * b = c;
    // This will generate a semantic error
}

Output:

error: lvalue required as left operand of assignment

When we have an expression on the left-hand side of an assignment operator (=), the program generates a semantic error. Even though the code is syntactically correct, the compiler does not understand the code.

Example 2:

#include <stdio.h>

void main() {
    int arr[5] = {5, 10, 15, 20, 25};
    
    int arraySize = sizeof(arr)/sizeof(arr[0]);
    
    for (int i = 0; i <= arraySize; i++)
    {
        printf("%d n", arr[i]);
    }
}

Output:


In the above example, we printed six elements while the array arr only had five. Because we tried to access the sixth element of the array, we got a semantic error and hence, the program generated a garbage value.

5. Linker Error

Linker is a program that takes the object files generated by the compiler and combines them into a single executable file. Linker errors are the errors encountered when the executable file of the code can not be generated even though the code gets compiled successfully. This error is generated when a different object file is unable to link with the main object file. We can run into a linked error if we have imported an incorrect header file in the code, we have a wrong function declaration, etc.

For Example:

#include <stdio.h>
 
void Main() { 
    int var = 10;
    printf("%d", var);
}

Output:

undefined reference to `main'

In the above code, as we wrote Main() instead of main(), the program generated a linker error. This happens because every file in the C language must have a main() function. As in the above program, we did not have a main() function, the program was unable to run the code, and we got an error. This is one of the most common type of linker error.

Conclusion

  • There are 5 different types of errors in C programming language: Syntax error, Runtime error, Logical error, Semantic error, and Linker error.
  • Syntax errors, linker errors, and semantic errors can be identified by the compiler during compilation. Logical errors and run time errors are encountered after the program is compiled and executed.
  • Syntax errors, linker errors, and semantic errors are relatively easy to identify and rectify compared to the logical and run time errors. This is so because the compiler generates these 3 (syntax, linker, semantic) errors during compilation itself, while the other 2 errors are generated during or after the execution.

The programmer should know the fact that there is very less
chances that a program will run perfectly in first time. It doesn’t matter how
nicely the designing is done and how much care is taken while coding. One can’t
say that the program would 100% error free. So the programmer has to make
efforts to detect and rectify any kind of errors that are present in the
program. But before detecting and removing errors it is much more necessary
that the programmer should know about the types of errors in programming. This article will
explain you about the types of errors in programming that must be taken care while writing
your program.

Types of Errors in Programming

Types of Errors in Programming

The types of errors are classified into four categories.
These are: syntax errors, logical errors, run-time errors and latent errors.

Syntax Errors

Any violation of rules and poor understanding of the
programming language results in syntax errors. The compiler can detect such
errors. If syntax errors are present in the program then the compilation of the
program fails and is terminated after showing the list of errors and the line
number where the errors have occurred. In some cases the line number may not
exactly indicate the correct place of the error. In some other cases, a single
syntax error can result in a long list of errors. Correction of one or two
errors in the program may remove the entire list of errors.

Run-time Errors

Runtime errors are the errors that occur during the
execution of the program. Some examples are, dividing by zero error,
insufficient memory for dynamic memory allocation, referencing an out-of-range
array element. These are not detected by compiler while compilation process. A
program with these kinds of errors will run but produce erroneous results or may
cause termination of program. Detection and removal of a run-time error is a
difficult task.

Logical Errors

As the name itself implies, these errors are related to the
logic of the program. Logical errors are also not detected by compiler and
cause incorrect results. These errors occur due to incorrect translation of
algorithm into the program, poor understanding of the problem and a lack of
clarity of hierarchy of operators. Consider following C statement:

if(a==b)

                printf(“Equaln”);

When a and b are float types values, they rarely become
equal due to truncation errors. The printf call may not be executed at all. A statement
like while(a!=b) might create an infinite loop.

Latent Errors

Latent Errors are the ‘hidden’ errors that occur only when a
particular set of data is used. Consider below example:

result = (a+b)/(c-d);

An error occurs only when c and d are equal because that
will make remainder zero (divide by zero error). Such errors can be detected
only by using all possible combinations of data.

Programming Errors in C

Introduction to Programming Errors in C

Errors, in general, are referred to as an action or fault or problem which is incorrect or makes the program behavior abnormal. In C programming language, the programming errors are bugs or faults that occur during runtime or compile time where the programs are not executed normally or can print any garbage values also. The process of removing or correcting these errors in C or any programming language is known as debugging. Therefore, for the programs to execute successfully they must be free from errors. There are warnings also generated by the compilers but they can be sometimes ignored as they rarely occur, while errors cannot be ignored as to obtain the desired outputs.

Types of Programming Errors in C with Examples

In C, there are different types of errors that can occur in the programs which can make programs run abnormally. Errors are occurred by beginners such as run time, compile-time errors, warnings, etc can be corrected in different ways.

Given below are the types of programming errors that occur in C programs:

1. Syntax Errors

These are the errors that occur during compiling the programs. These errors are compile-time errors. As these syntax errors are thrown by the compilers during the program execution hence these syntax errors are called compilation errors. In general, these errors are made while writing programs or the syntax writing rules are not followed while writing the programs. Such errors can be easily corrected as they are known. These types of errors are usually made by beginners who are learning the programming language.

Example:

Suppose we want to declare any variable with particular data type then the correct method or syntax for declaring variable is as below:

Syntax:

int a;

But if we do as

Int a;

Then the above declaration gives syntax error as to letter “I” for data type “int” is in the capital letter so.

Code:

#include <stdio.h>
intmain()
Int a = 10;
printf("The value of a is : %d", a);
return 0;
}

Output:

programming errors in c 1

In the above program, we saw the data type was written wrong so it gave compilation failed due to the error and due to the occurrence of this error the program could not be executed. The syntax error can be like not mentioning data type before the variable, or not terminating the printf statement with a semicolon (;), not ending the program with flower brackets ( {} ), etc.

2. Runtime Error

This error has occurred during runtime which means that occurs during program execution that is after compilation of the program. This error occurs mainly when the program is still running and it will not be able to perform some particular operation in the main which may lead to memory leakage.

Example:

Code:

#include<stdio.h>
intmain()
{
int n = 9;
int div = 0;
int rem = n/0;
printf("Result of division = %d", rem);
}

Output:

programming errors in c2

The above program gives the divide by zero error during the program execution which can be handled by using exceptions.

3. Linker Error

This error has occurred when the executable file is not found or not created. This can be explained suppose if the main.c contains some function like func() whose executable file is func.c, this func() is defined in some other file such as sample.c and the object files generated are main.o and sample.o when the program is executing if the func() definition is not found in the sample.o then the linker will throw an error.

Example:

Code:

#include <stdio.h>
intMain()
{
int n=9;
printf("The value of n is : %d",n );
return 0;
}

Output:

linker

In the above program, the error occurred because of writing “Main” instead of “main” which is the most common linker error.

4. Semantic Error

These errors have occurred when the program statements are not correctly written which will make the compiler difficult to understand such as the use of the uninitialized variable, type compatibility, errors in writing expressions, etc.

Example:

Code:

#include <stdio.h>
intmain()
{
intx,y,res;
x=2;
y=3;
res=1;
x+y=res;
return 0;
}

Output:

semantic

In the above program, the variable “res” cannot be used twice as the left operand.

5. Logical Error

This is an error that gives incorrect output due to illogical program execution but they seem to be error-free hence they are called logical errors.

Example:

Code:

#include <stdio.h>
intmain()
{
int sum=0;
int a=1;
for(inti=1;i<=20;i++);
{
sum=sum+a;
a++;
}
printf("The sum of the numbers is %d", sum);
return 0;
}

Output:

logical

The above program is to print the output as the sum of numbers less than 20, but as we have specified semicolon after the for loop statement so it gives the wrong output where statements inside for loop are not executed. Hence the logical error occurs by printing the sum of 20 numbers as 1.

Conclusion

In this article, we have discussed the programming errors that are occurred in C programming languages. To conclude with this article is that there are different types of errors that occur, which can be occurred due to the writing the programs incorrectly, or by writing the wrong syntax, or by writing wrong expressions in programs, or by not following the rules of writing programs such as case sensitive is not followed, etc. In this article, we have discussed the main errors such as runtime errors, compile-time errors, syntax errors, semantic errors, and logical errors.

Recommended Articles

This is a guide to Programming Errors in C. Here we discuss the introduction to types of programming errors in C with 5 different errors and respective sample code. You may also have a look at the following articles to learn more –

  1. Arrays in C Programming
  2. Leap Year Program in C
  3. Constants in C
  4. Types of Errors in C

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Error is an illegal operation performed by the user which results in abnormal working of the program. 
    Programming errors often remain undetected until the program is compiled or executed. Some of the errors inhibit the program from getting compiled or executed. Thus errors should be removed before compiling and executing. 
    The most common errors can be broadly classified as follows.
     

    Type of errors:

    1. Syntax errors: Errors that occur when you violate the rules of writing C/C++ syntax are known as syntax errors. This compiler error indicates something that must be fixed before the code can be compiled. All these errors are detected by compiler and thus are known as compile-time errors. 
      Most frequent syntax errors are: 
      • Missing Parenthesis (})
      • Printing the value of variable without declaring it
      • Missing semicolon like this:

    C++

    #include <iostream>

    using namespace std;

    void main()

    {

        int x = 10;

        int y = 15;

        cout << " "<< (x, y)

    }

    C

    #include<stdio.h>

    void main()

    {

        int x = 10;

        int y = 15;

        printf("%d", (x, y))

    }

    Error: 

    error: expected ';' before '}' token
    • Syntax of a basic construct is written wrong. For example : while loop

    C++

    #include <iostream>

    using namespace std;

    int main(void)

    {

        while(.)

        {

            cout <<"hello";

        }

        return 0;

    }

    C

    #include<stdio.h>

    int main(void)

    {

        while(.)

        {

            printf("hello");

        }

        return 0;

    }

    Error:

    error: expected expression before '.' token
         while(.) 
    • In the given example, the syntax of while loop is incorrect. This causes a syntax error.
    1. Run-time Errors : Errors which occur during program execution(run-time) after successful compilation are called run-time errors. One of the most common run-time error is division by zero also known as Division error. These types of error are hard to find as the compiler doesn’t point to the line at which the error occurs. 
      For more understanding run the example given below. 
       

    C++

    #include <iostream>

    #include <bits/stdc++.h>

    using namespace std;

    void main()

    {

        int n = 9, div = 0;

        div = n/0;

       cout << "result = "<< div;

    }

    C

    #include<stdio.h>

    void main()

    {

        int n = 9, div = 0;

        div = n/0;

        printf("result = %d", div);

    }

    Error:

    warning: division by zero [-Wdiv-by-zero]
         div = n/0;
    1. In the given example, there is Division by zero error. This is an example of run-time error i.e errors occurring while running the program.
    2. Linker Errors: These error occurs when after compilation we link the different object files with main’s object using Ctrl+F9 key(RUN). These are errors generated when the executable of the program cannot be generated. This may be due to wrong function prototyping, incorrect header files. One of the most common linker error is writing Main() instead of main()
       

    C++

    #include <bits/stdc++.h>

    using namespace std;

    void Main()

    {

        int a = 10;

        cout << " "<< a;

    }

    C

    #include<stdio.h>

    void Main()

    {

        int a = 10;

        printf("%d", a);

    }

    Error: 

    (.text+0x20): undefined reference to `main'
    1. Logical Errors : On compilation and execution of a program, desired output is not obtained when certain input values are given. These types of errors which provide incorrect output but appears to be error free are called logical errors. These are one of the most common errors done by beginners of programming. 
      These errors solely depend on the logical thinking of the programmer and are easy to detect if we follow the line of execution and determine why the program takes that path of execution. 
       

    C++

    int main()

    {

        int i = 0;

        for(i = 0; i < 3; i++);

        {

           cout << "loop ";

            continue;

        }

        return 0;

    }

    C

    int main()

    {

        int i = 0;

        for(i = 0; i < 3; i++);

        {

            printf("loop ");

            continue;

        }

        getchar();

        return 0;

    }

    1. No output
    2. Semantic errors : This error occurs when the statements written in the program are not meaningful to the compiler.

    C++

    int main()

    {

        int a, b, c;

        a + b = c;

    }

    C

    void main()

    {

      int a, b, c;

      a + b = c;

    }

    Error:

     error: lvalue required as left operand of assignment
     a + b = c; //semantic error

    This article is contributed by Krishna Bhatia. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
    Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
     

    Reading time: 30 minutes | Coding time: 5 minutes

    Error handling signifies the techniques you will use to handing possible errors that the code might encounter during runtime. Handling errors are important as by doing this, we can prevent abrupt termination of a program and make it follow a deterministic path thus, giving a good user experience. Preventing all errors might not be possible as the possible situation space is large and hence, handling errors at runtime is an important strategy.

    C does not support direct dealing with error handling (i.e. Exception handling) like languages such as Java and Python but still there are several ways by which we can do error handling in C.

    How error handling work in C?

    We have several methods and variables in error.h header file that can be used to point out the error in C by return statement in function. In C when some error occurs then -1 or NULL value is returned and a global variable errno is set with the error code.Hence we use returned values to check errors.
    Whenever a function call is made in C language, a variable named errno is associated with it. It is a global variable, which can be used to identify which type of error was encountered while function execution, based on its value.

    Several functions for error handling

    • perror(): returns the string passed to it along with the textual represention of the current errno value.
    • strerror() This method returns a pointer to the string representation of the current errno value.

    Several error situations

    Following are the errors that are defined within C and which might occur during program execution:

    Erroe number value Error
    1. Operation Not permitted
    2. No such File or directory
    3. No such process
    4. Interrupted system call
    5. I/O error
    6. No such device or address
    7. Argument list too long
    8. Exec format error
    9. Bad file number
    10. No child processes
    11. Try again
    12. Out of memory
    13. Permission denied

    Question

    Which of the following is corresponding to errno value «2»

    No such file or directory

    Argument list too long

    Try again

    Exec format error

    The error corresponding to errno value 2 is «No such file or directory» and it appears when the file or directory being accessed is not existing in the respective location.

    Let’s see several errors in C and how to tackle them.

    1. Divide by zero error in C

    Most common error that we face in C is divide by zero error and many times we stuck into this while programming.
    C does not have any special function or class to deal with such type of error but we can simply overcome it by checking the divisor before the division.Let us understand by following example.
    Let’s see when does divide by zero error comes.

    #include<stdio.h> 
    #include<stdlib.h>
    int main() 
    { 
    	int y=10/0;
    	printf("result is: %.2f", y); 
    	
    } 
    

    OUTPUT

    6

    Now we overcome this error by separate cases and display error.

    #include<stdio.h> 
    #include<stdlib.h>
    int main() 
    { 
    	int divisor = 0; 
        float y;
        if (divisor==0) 
    	{ 
    		printf("Division by Zero is not allowed"); 
            fprintf(stderr, "Division by zero! Exiting...n"); 
            //fprintf is used to print something in a file here stderr 
    		return -1;
    	} 
    	else
    	{ 
    		y = 10 / divisor; 
    		printf("result is: %.2f", y); 
    	} 
    } 
    

    divisonbyzero

    Error no 2. No such file or directory

    This error comes if we try to access or open a file that does not exist in the required location and following is code to display suitable error for that puropse.

    #include <stdio.h>       
    #include <errno.h>       
    #include <string.h> 
     
    int main ()
    {
        FILE *fp;
        fp = fopen("a.txt", "r");
         //perform operation on fp
        //we are opening a file that does not exist
     
        return 0;
    }
    

    7

    To overcome this error we check prior if file is there or not and then proceed accordingly.By using ptr!=NULL we ensure that the file does not exist and hence instead of performing operation we display suitable error message.

    #include <stdio.h>       
    #include <errno.h>       
    #include <string.h> 
    
    int main ()
    {
        FILE *fp;
        fp = fopen("a.txt", "r");
        if(fp==NULL)
        {
    	printf("Value of errno: %dn ", errno);
        printf("The error message is : %sn", strerror(errno));
        perror("Message from perror");	
    	}
        else{
    		printf("correct");
    		//perform task to be done on given file
        }
       return 0;
    }
    

    err2-1

    3. Use of EXIT_SUCCESS ,EXIT_FAILURE to deal with errors

    This error handling is used in C as it is considered a good approach to use exit() in function and show it’s status ,i.e. the it is a failure or success by EXIT_SUCCESS and EXIT_FAILURE .EXIT_SUCCESS is a macro defined by 0 and EXIT_FAILURE is defined by -1 .Following is the example of the it.

    #include <stdio.h> 
    #include <errno.h> 
    #include <string.h> 
    #include <stdlib.h> 
    
    int main () 
    { 
    	FILE * fp; 
    	fp = fopen ("filedoesnotexist.txt", "rb"); 
    
    	if (fp == NULL) 
    	{ 
    		printf("Value of errno: %dn", errno); 
    		printf("Error opening the file: %sn", 
    							strerror(errno)); 
    		perror("Error printed by perror"); 
    
    		exit(EXIT_FAILURE); 
    		printf("I will not be printedn"); //line below exit() is not executed 
    	} 
    
    	else
    	{ 
    		fclose (fp); 
    		exit(EXIT_SUCCESS); 
    		printf("I will not be printedn"); 
    	} 
    	return 0; 
    } 
    

    s3

    4. Error no 9 Bad File Number Error

    In general, when «Bad File Descriptor» occurs, it means that the socket file descriptor you passed into the API is not valid, which has multiple possible reasons:

    a)The fd is already closed somewhere.
    b)The fd has a wrong value and is inconsistent with value from socket() api.

    #include <sys/epoll.h>
    #include <stdio.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    #include <string.h>
    #include <sys/uio.h>
      
      int main() {
        struct epoll_event event ;
        int ret,fd, epfd ;
      
        fd = open("doc", O_RDONLY);//as this file does not exist thus error for this is got too
        if( fd < 0 )
          perror("open");
      
        event.data.fd = fd ;
        event.events = EPOLLIN|EPOLLOUT ;
      
        epfd = epoll_create(50);
        printf("%d", epfd );
      
        if( epfd < 0 )
          perror("epoll_create");
      
        ret = epoll_ctl( epfd, EPOLL_CTL_ADD, fd, &event ) ;
        if( ret < 0 )
          perror("epoll_ctl");}
    

    open1

    Hence we get this error here as we are trying to open regular files and functions like epoll(), select(), and poll() does not work on regular files.
    However if it is a pipe or socket then ,then do as:
    $mkfifo doc

    Besides these there are several other errors in C

    Syntax error :

    Errors that occur when you do not follow the rules of writing C syntax is known as syntax errors. This is a compiler error which indicates something that must be fixed before the code can be compiled. All these errors are detected by compiler and thus are known as compile-time errors.Following is the example:-

    #include<stdio.h> 
    #include<string.h>
    int main() 
    { 
        int x = 10; 
        int y = 15;  
          
        printf("%d", (x, y)) // semicolon missed  
        getch();
        return 0;
    } 
    

    In order to remove this error , one needs to make sure that the syntax is written correctly else they will find errors like this:-

    8

    Logical error

    On compilation and execution of a program, desired output is not obtained when certain input values are given. These types of errors provide incorrect output but it seems that there is no error. They are called logical errors.
    These errors depend on the logical thinking of the programmer and are easy to be found if we follow the code and determine why the program gave certain result.Hence to overcome them one needs to find out if the result comes different than what is expected.One can use different ‘printf’ statements to find out the exact line showing wrong working.Following is the example:-

    #include<stdio.h>
    #include<string.h>
    int main() 
    { 
    	int i = 0; 
    	for(i = 0; i < 3; i++); //logical error due to ;
    	{ 
    		 printf("hello");
    	} 
    	getchar(); 
    	return 0; 
    } 
    

    Given code is done as :-

    Repeat five times for (i=0;i<3;i++)
    ... do nothing (semicolon)
    Open a new scope for local variables {
    ... Print "hello"
    Close the scope }.Hence the ouput is:-
    

    99-1

    Semantic Error

    This error occurs when the statements written in the program are not adding meaning to the compiler.

    #include<stdio.h>
    #include<string.h>
    int main() 
    { 
      int a, b, c; 
      a + b = c; //semantic error 
    	getchar(); 
    	return 0; 
    } 
    

    00

    One has to ensure the code correctness to overcome such error.
    There are other errors like Operation not permitted (like when you try to write in a file that is opened in read mode only.);Out of memory(occur when several process run at the same time)…etc.

    Hence use suitable code with correct approach to avoid such errors.

    While writing c programs, errors also known as bugs in the world of programming may occur unwillingly which may prevent the program to compile and run correctly as per the expectation of the programmer.

    Basically there are three types of errors in c programming:

    1. Runtime Errors
    2. Compile Errors
    3. Logical Errors

    C runtime errors are those errors that occur during the execution of a c program and generally occur due to some illegal operation performed in the program.

    Examples of some illegal operations that may produce runtime errors are:

    • Dividing a number by zero
    • Trying to open a file which is not created
    • Lack of free memory space

    It should be noted that occurrence of these errors may stop program execution, thus to encounter this, a program should be written such that it is able to handle such unexpected errors and rather than terminating unexpectedly, it should be able to continue operating. This ability of the program is known as robustness and the code used to make a program robust is known as guard code as it guards program from terminating abruptly due to occurrence of execution errors.

    Compile Errors

    Compile errors are those errors that occur at the time of compilation of the program. C compile errors may be further classified as:

    Syntax Errors

    When the rules of the c programming language are not followed, the compiler will show syntax errors.

    For example, consider the statement,

    int a,b:
    

    The above statement will produce syntax error as the statement is terminated with : rather than ;

    Semantic Errors

    Semantic errors are reported by the compiler when the statements written in the c program are not meaningful to the compiler.

    For example, consider the statement,

    b+c=a;
    

    In the above statement we are trying to assign value of a in the value obtained by summation of b and c which has no meaning in c. The correct statement will be

    a=b+c;
    

    Logical Errors

    Logical errors are the errors in the output of the program. The presence of logical errors leads to undesired or incorrect output and are caused due to error in the logic applied in the program to produce the desired output.

    Also, logical errors could not be detected by the compiler, and thus, programmers has to check the entire coding of a c program line by line.

    Errors are the problems or the faults that occur in the program, which makes the behavior of the program abnormal, and experienced developers can also make these faults. Programming errors are also known as the bugs or faults, and the process of removing these bugs is known as debugging.

    These errors are detected either during the time of compilation or execution. Thus, the errors must be removed from the program for the successful execution of the program.

    There are mainly five types of errors exist in C programming:

    • Syntax error
    • Run-time error
    • Linker error
    • Logical error
    • Semantic error

    Programming Errors in C

    Syntax error

    Syntax errors are also known as the compilation errors as they occurred at the compilation time, or we can say that the syntax errors are thrown by the compilers. These errors are mainly occurred due to the mistakes while typing or do not follow the syntax of the specified programming language. These mistakes are generally made by beginners only because they are new to the language. These errors can be easily debugged or corrected.

    For example:

    Commonly occurred syntax errors are:

    • If we miss the parenthesis (}) while writing the code.
    • Displaying the value of a variable without its declaration.
    • If we miss the semicolon (;) at the end of the statement.

    Let’s understand through an example.

    Output

    Programming Errors in C

    In the above output, we observe that the code throws the error that ‘a’ is undeclared. This error is nothing but the syntax error only.

    There can be another possibility in which the syntax error can exist, i.e., if we make mistakes in the basic construct. Let’s understand this scenario through an example.

    In the above code, we put the (.) instead of condition in ‘if’, so this generates the syntax error as shown in the below screenshot.

    Output

    Programming Errors in C

    Run-time error

    Sometimes the errors exist during the execution-time even after the successful compilation known as run-time errors. When the program is running, and it is not able to perform the operation is the main cause of the run-time error. The division by zero is the common example of the run-time error. These errors are very difficult to find, as the compiler does not point to these errors.

    Let’s understand through an example.

    Output

    Programming Errors in C

    In the above output, we observe that the code shows the run-time error, i.e., division by zero.

    Linker error

    Linker errors are mainly generated when the executable file of the program is not created. This can be happened either due to the wrong function prototyping or usage of the wrong header file. For example, the main.c file contains the sub() function whose declaration and definition is done in some other file such as func.c. During the compilation, the compiler finds the sub() function in func.c file, so it generates two object files, i.e., main.o and func.o. At the execution time, if the definition of sub() function is not found in the func.o file, then the linker error will be thrown. The most common linker error that occurs is that we use Main() instead of main().

    Let’s understand through a simple example.

    Output

    Programming Errors in C

    Logical error

    The logical error is an error that leads to an undesired output. These errors produce the incorrect output, but they are error-free, known as logical errors. These types of mistakes are mainly done by beginners. The occurrence of these errors mainly depends upon the logical thinking of the developer. If the programmers sound logically good, then there will be fewer chances of these errors.

    Let’s understand through an example.

    Output

    Programming Errors in C

    In the above code, we are trying to print the sum of 10 digits, but we got the wrong output as we put the semicolon (;) after the for loop, so the inner statements of the for loop will not execute. This produces the wrong output.

    Semantic error

    Semantic errors are the errors that occurred when the statements are not understandable by the compiler.

    The following can be the cases for the semantic error:

    • Use of a un-initialized variable.
      int i;
      i=i+2;
    • Type compatibility
      int b = «javatpoint»;
    • Errors in expressions
      int a, b, c;
      a+b = c;
    • Array index out of bound
      int a[10];
      a[10] = 34;

    Let’s understand through an example.

    In the above code, we use the statement a+b =c, which is incorrect as we cannot use the two operands on the left-side.

    Output

    Programming Errors in C


    Понравилась статья? Поделить с друзьями:
  • Error while processing saml response перевод
  • Error while processing function call
  • Error while powering on vmware player failed to start the vmware authorization service
  • Error while powering on vmware player cannot connect to the virtual machine
  • Error while powering on unable to open kernel device vmcidev vmx