What causes run time errors in a C++ program?
The basic causes that I have encountered as per my Competitive Coding Experience are :
- Invalid memory access during run-time.
- #include <iostream>
- using namespace std;
- int arr[5];
- int main()
- {
- int ans=arr[-1];
- cout<<ans<<endl;
- return 0;
- }
2. Accessing linked list nodes that do not exist.
- Consider a Linked List :
- 1->2->3->NULL
- cout<<head->next->next->next->data<<endl;
- // head->next->next->next is actually NULL.
3. Dividing by zero.
- #include <iostream>
- using namespace std;
- int main()
- {
- int ans=5/0;
- cout<<ans<<endl;
- return 0;
- }
4. Some online judges consider segmentation faults also as run-time errors.
- #include <iostream>
- using namespace std;
- 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.
- #include <iostream>
- using namespace std;
- int arr[1000000000]; //Note the size of the array.
- //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).
- #include <iostream>
- using namespace std;
- int main() {
- int arr[1000000000];
- return 0;
- }
6. Making a silly mistake such as this.
- #include<bits/stdc++.h>
- long long int x;
- 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