The 6 most common causes of runtime errors and how to fix them

Programming Pathshala
5 min readMar 11, 2022

--

After putting hours of effort in designing the algorithm and implementing the code, the worst that a programmer can encounter are run time errors. Often, by the time we have finished coding and have submitted the problem, we are so mentally drained that seeing a runtime error just evokes one emotion: “Why me”. A runtime error could mean ANYTHING, and in all probability requires you to read the whole code again and again to be able to figure out the source of error. This could lead to hours of tedious debugging. But not anymore.

Here, we will discuss the most common 6 run-time errors. Once you become familiar with these different types of errors, locating them in your code will be much easier and reduce 50% of your debugging time.

  1. Index out of bounds/negative array index — accessing an index that is not part of the array yet
#include <iostream>
#include <vector>
using namespace std;
int main() {
// your code goes here
vector<int> arr = vector<int>();

int n,sum = 0;
cin>>n;
for(int i=0;i<n;i++){
cin>>arr[i];
sum = sum+arr[i];
}
cout<<sum;
return 0;
}

Try to run this simple program for finding the sum of n numbers with some input.
You will see a runtime error. Why?

Its because the vector arr is empty, it has no elements. Trying to access the element at index i using arr[i] is an error, because the size of vector is still 0. There can be multiple approaches to fix this:

i) Declare the size of vector at the beginning

 vector<int> arr = vector<int>(10000);

Preferred when the input size has a defined upper limit.

ii) Or declare the vector after reading the input size, n,

 cin>>n;
vector<int> arr = vector<int>(n);

iii) Or increase the size of vector by 1 every time you take the input

//remove already added elements from previous test cases
arr.clear();
for(int i=0;i<n;i++){
int temp;
cin>>temp;
arr.push_back(temp); // creating a new(ith) elemen
sum = sum+arr[i];
}

The last approach can cause unforeseen trouble if you are not careful( e.g. in problems that have multiple test cases, you could be adding inputs of the new test case behind the inputs of the previous test case). Make sure you clear your vector for every test case.

NOTE: In C++, if you are using vectors, arr.at(i) is much safer to use. arr[i] may not throw runtime error, and can give you unexpected results when i is out of bounds, and make debugging insanely difficult.

2. Declaring a very large array/requesting a large chunk of memory

int size = 1e7;int arr[size]; //array of 1e7 size

If the program tries to request memory that is more than the maximum memory limit for the program, it causes run time error. The limit can be different depending on the platform, or for different problems.
Generally, the maximum size of int array that you can declare is in range 10⁶-10⁷

Possible fixes:

i. See if instead of int array you can use short array/bool array.

That may reduce the required space enough to evade runtime error

ii. Try to solve the problem without using such a big array.

The problem is meant to be solved by using less memory by some other technique. E.g. at first glance the following problem from codeforces looks like it can be solved using arrays, but when you see the constraint, you will find the 2D array’s size will be more than 10⁸. But the problem is solvable even without using such a large array

3. Recursion limit breach/stack overflow

Take the example of a simple program to find factorial of any non-negative integer.

#include <iostream>
#include <vector>
using namespace std;
long long int factorial(long long int n)
{
if(n==1)
return 1;
long long int x = factorial(n-1);
return n*x;
}
int main() {
//cout<<factorial(1);
cout<<factorial(0);
}

The recursive function looks correct, with base case declared and all. But the program will either cause TLE or runtime error. Why? Because base case 0 is not handled.
Factorial(0) will go on calling factorial(-1) factorial(-2) etc… indefinitely until it shows TLE or RTE due to recursion limit breach/stack overflow.

Fix: Carefully think about all the base cases and prevent recursion “leakage”

4. Division/modulus with zero/ sqrt of negative number

Anywhere in the code with a%b or a/b is a potential candidate for run time error: due to division by 0

5. Parsing input line

import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
BufferedReader inp = new BufferedReader (new InputStreamReader(System.in));
int T= Integer.parseInt(inp.readLine()); // for taking a number as an input
System.out.println(T);
String str = inp.readLine(); // for taking a string as an input
}
}

The above program is just taking an integer input and printing it. Try to insert a space after the integer input and see what happens. It will cause a runtime error. Always trim the leading/trailing spaces while parsing input. In JAVA, it can be done using trim().

6. Integer Overflow

#include <iostream>
#include <vector>
using namespace std;


int main() {
// your code goes here
int temp;
vector<int> x= vector<int>(40000);
for(short int i=0;i<40000;i++){
temp = x.at(i);
}
return 0;
}

Integer overflow itself may not cause run time error, but it can indirectly cause run time error, as in above example. The above loop is supposed to run 40000 times, till i=0 to i=39,999. But after the value of i becomes 32767, incrementing it results in overflow and the value of i is set to -32768. This error is known as overflow. As a result, x.at(i) will throw negative index error, since the code is trying to access negative index of the vector x.

Fix: read the input constraints and choose the type of variables accordingly. If the value of a variable needs to go till n, make sure the variable/data type is capable to store the value of n

These are the basic and most common sources of run time errors. Anytime you get a runtime error, search for these 6 patterns in the code, and one of them will definitely be the key to fixing your code.

In the next article in this series, we will take a look at a technique to zero down the source of run time error in just a few clicks, WITHOUT having to go through the complete code once again.

--

--

Programming Pathshala
Programming Pathshala

Written by Programming Pathshala

We are working to democratise access to Tech Education. We help students learn coding and be confident about themselves.

No responses yet