为什么我在 C 中通过在堆栈上声明一个大数组而得到一个段错误? [英] Why do I get a segfault in C from declaring a large array on the stack?

查看:19
本文介绍了为什么我在 C 中通过在堆栈上声明一个大数组而得到一个段错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从这行代码中得到一个段错误:

I get a segfault from this line of code:

int fatblob[1820][286][5];

这是为什么呢?

推荐答案

你正在尝试分配 1820 * 285 * 5 * sizeof(int) 字节 = 大约 10MB(如果 sizeof(int) == 4).这可能比您的操作系统默认为您提供的堆栈分配字节数更多,因此您会遇到堆栈溢出/段错误.

You're trying to allocate 1820 * 285 * 5 * sizeof(int) bytes = about 10MB (if sizeof(int) == 4). That's probably more bytes than your OS gives you for stack allocation by default, so you get a stack overflow/segfault.

您可以通过在创建线程时请求额外的堆栈、在堆上分配或更改操作系统默认值来解决此问题.

You can fix this by either asking for extra stack when you create the thread, allocating on the heap, or changing the OS defaults.

这篇关于为什么我在 C 中通过在堆栈上声明一个大数组而得到一个段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆