计算需要删除多少列才能使每一行在 C++ 中排序


C++ 程序的异常行为通常会导致程序崩溃。您可能遇到过段错误、中止、浮点异常等问题。以下是可能帮助您了解 C++ 程序崩溃原因的一些示例程序。

异常

C++ 中的异常是程序在遇到异常情况时的响应。如果这些异常没有使用 try-catch 块正确处理,则程序会因这些异常而崩溃。以下程序由于除以零异常而崩溃:

示例

#include <iostream>
int main(){
   int num1=10;
   int num2=0;
   int quotient=num1/num2;
   printf("\n Quotient is: %d",quotient);
   return 0;
}

输出

Floating point exception (core dumped)

缓冲区溢出

缓冲区是一个临时存储区域。当程序向缓冲区写入数据时超过缓冲区可容纳的大小,额外的数据会超出缓冲区的边界。数据会覆盖到相邻的内存位置。当输入超过变量 num 可容纳的大小时,以下程序的行为会发生改变。

示例

#include <iostream>
#include <string.h>
int main(){
   int num=100;
   std::cout<<"\nValue for num:"<<num;
   char c[2];
   strcpy(c,"abcdefghijklmnopqrstuvwxyz");
   std::cout<<"\nValue for c:"<<c;
   return 0;
}

输出

Value for num:100
Segmentation fault (core dumped)

堆栈溢出

堆栈溢出问题发生在调用堆栈指针超过堆栈边界时。堆栈包含有限的空间。当程序使用的空间超过堆栈上可用空间时,则称堆栈溢出并导致程序崩溃。最常见的原因是无限递归。

以下程序包含对函数 factorial() 的无限次调用。在这种情况下,return 语句不正确。

示例

#include <iostream>
#include <string.h>
int factorial(int num){
   if(num==0)
      return 1;
   else
      return(factorial(num));
}
int main(){
    int n=10;
   int fact=factorial(n);
   std::cout<<fact;
}

输出

Segmentation fault (core dumped)

段错误

段错误或核心转储发生在程序尝试访问不属于它的内存位置时。在下面的程序中,指针 str 正在无限期地递增和追加内存。

示例

#include <iostream>
int main(){
   char *str;
   char name[]="iostream";
   str=name;
   while(1)
      (*str++)='a';
}

输出

Segmentation fault (core dumped)

内存泄漏

内存泄漏发生在动态分配的内存从未被释放时。内存必须在不再使用时释放。如果我们不断地分配内存,那么这些内存泄漏最终会随着时间的推移而增加,并最终导致程序崩溃。如下所示的劣质代码的重复会导致内存泄漏:

示例

#include <iostream>
int main(){
    int *node;
   node = (int *) malloc(9999999);
   // free(node);
}

更新于:2020-7-28

67 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.