What causes run time errors in a C++ program?

The basic causes that I have encountered as per my Competitive Coding Experience are :
  1. Invalid memory access during run-time.
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int arr[5];
  5. int main()
  6. {
  7. int ans=arr[-1];
  8. cout<<ans<<endl;
  9. return 0;
  10. }
2. Accessing linked list nodes that do not exist.
  1. Consider a Linked List :
  2. 1->2->3->NULL
  3.  
  4. cout<<head->next->next->next->data<<endl;
  5. // head->next->next->next is actually NULL.
3. Dividing by zero.
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int main()
  5. {
  6. int ans=5/0;
  7. cout<<ans<<endl;
  8. return 0;
  9. }
4. Some online judges consider segmentation faults also as run-time errors.
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int arr[5];
Now suppose in the above example we try to access arr[10] during run-time then a segmentation error occurs which is also treated as run-time errors by many Online Judges for example Leetcode and Interviewbit among others.
5. Large allocation of memory together/Large Static Memory Allocation.
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int arr[1000000000]; //Note the size of the array.
  5. //In general around upto 10^8 is usually accepted by all online judges. However to be on the safe side use upto 10^7 unless required.
Try executing the following on your offline compiler (Devcpp for example).
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int main() {
  5. int arr[1000000000];
  6. return 0;
  7. }
6. Making a silly mistake such as this.
  1. #include<bits/stdc++.h>
  2. long long int x;
  3. scanf("%d",&x);
The above code gives run-time error. The reason being x is long long int and scanf should use %lld. I have got a lot of run-time errors for this on online judges such as Codechef.

No comments

Most View Post

Recent post

Codeforces Round 971 (Div. 4) 2009C. The Legend of Freya the Frog Solution

  Problem Link    https://codeforces.com/contest/2009/problem/C S olution in C++: /// Author : AH_Tonmoy #include < bits / stdc ++. h &g...

Powered by Blogger.