📜  C / C++中运行时错误的原因

📅  最后修改于: 2021-05-30 17:04:11             🧑  作者: Mango

在本文中,我们将讨论运行时错误的原因及其解决方案。

运行时错误:程序中的运行时错误是在成功编译程序后运行该程序时发生的错误。下面是一些确定运行时错误背后原因的方法:

方法1:当数组的索引分配有负索引时,它将导致在运行时错误期间无效的内存访问。下面是C++程序,用于说明运行时的无效内存访问:

C++
// C++ program to illustrate invalid
// memory access during run-time
#include 
using namespace std;
  
// Global declaration
int arr[5];
  
// Driver Code
int main()
{
    int answer = arr[-10];
    cout << answer;
  
    return 0;
}


C++
// C++ program to illustrate
// array runs out of bound
#include 
using namespace std;
  
// Driver Code
int main()
{
    long n;
    n = 100000000000;
  
    // 'n' is out of bound for
    // the array limit
    long a[n];
  
    cout << a[1] << " ";
    return 0;
}


C++
// C++ program to illustrate runtime
// error by un-assigned variables
#include 
using namespace std;
  
// Driver Code
int main()
{
    long long N;
  
    // N is assigned garbage value
    long arr[N];
  
    cin >> N;
  
    for (int i = 0; i < N; i++) {
        cin >> arr[i];
    }
  
    for (int i = 0; i < N; i++) {
        cout << arr[i] << " ";
    }
  
    return 0;
}


输出:
1736487104

方法2:有时,数组或向量超出其限制的范围,导致运行时错误。下面是说明数组超出范围的C++程序:

C++

// C++ program to illustrate
// array runs out of bound
#include 
using namespace std;
  
// Driver Code
int main()
{
    long n;
    n = 100000000000;
  
    // 'n' is out of bound for
    // the array limit
    long a[n];
  
    cout << a[1] << " ";
    return 0;
}

输出:

解释:

  • 这是索引超出范围的错误。
  • 可以通过使用数组/向量的大小来解决这个问题。

方法3:匆忙编码时遇到一些愚蠢的错误,有时会导致运行时错误。下面是C++程序,它通过未分配的变量说明运行时错误:

C++

// C++ program to illustrate runtime
// error by un-assigned variables
#include 
using namespace std;
  
// Driver Code
int main()
{
    long long N;
  
    // N is assigned garbage value
    long arr[N];
  
    cin >> N;
  
    for (int i = 0; i < N; i++) {
        cin >> arr[i];
    }
  
    for (int i = 0; i < N; i++) {
        cout << arr[i] << " ";
    }
  
    return 0;
}

输出:

解释:

上面的程序显示“错误的内存访问(SIGBUS)”,因为:

  • 在此,为变量N分配了垃圾值,从而导致运行时错误。
  • 有时,由于取决于编译器,因此如何分配垃圾值。
  • 可以通过在扫描变量n的值后声明arr [N]并检查其是否为数组/矢量索引的上限或下限来解决此问题。
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”