c - 基于程序运行时的崩溃

标签 c crash

在下面的程序中,当用户输入 720 时程序崩溃。为什么?

main()
{   
  for (;;) 
  { 
    int depth,i,j; 
    printf("enter the depth");  
    scanf("\n%d",&depth);   
    printf("first");    
    int arr[depth][depth];//at this line the program get crashed //
    printf("first1"); 
    for(i=0;i<depth;i++)    
    {
      for(j=0;j<=i;j++)         
      {         
        arr[i][j]=i+1;      
      }
    }       
    for(i=0;i<depth;i++)    
    { 
        printf("\n");       
        for(j=0;j<=i;j++)       
        {           
          printf("%d\t",arr[i][j]);         
        }
    }
  }
}

最佳答案

在堆栈上分配了一个类似的数组。如果用户输入 720,您将获得一个大小为 720*720*sizeof(int) 字节的数组。在具有 32 位 int 的系统上,这几乎是 2MB。您可能会确切地知道这个网站的名字:堆栈溢出!

相反,在堆上分配:

int **arr = malloc(depth * depth * sizeof(int));

稍后您需要使用free(arr); 释放内存。

关于c - 基于程序运行时的崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30576033/

相关文章:

c - 使用 mingw-w64 与 GLFW 链接错误

iphone - 修改 XIB 文件后应用程序崩溃

printing - Cordova -插件打印机崩溃的Ionic2应用程序

wordpress - IE8 崩溃打开安装了 Gantry 框架的 WordPress

iphone - UITableView 在动画过程中崩溃,已找到解决方案,但没有找到根本原因,想知道为什么?

c++ - 是什么导致存储的std::list::iterator无效?

c - 是否有检查名为 sptr 的 sockaddr* 是否指向 ipv4 或 ipv6 地址的函数?

c - 纯 C 标准输入缓冲区垃圾和换行符

c - 来自 gets() 的输入与保存在 char 数组中的值不匹配

检查c中字符串的最后一个字符