c - 初始化大 vector 时出现段错误

标签 c segmentation-fault

<分区>

Possible Duplicate:
C programming, why does this large array declaration produce a segmentation fault?

为什么这个程序会崩溃?它适用于最大 1e6,如果我不将每个值都设置为 0,它也能正常工作。

程序没有分配所有内存吗?

int main() {
    const int max = 10000000; // 1e7
    int end[max];
    unsigned int i;
    for ( i = 0; i < max; i++ )
        end[i] = 0;
}


$ gcc test.c && ./a.out 
Segmentation fault (core dumped)

最佳答案

变长数组通常分配在上。堆栈空间有限;您可能在这里遇到堆栈溢出。您不能在这样的内存位置上分配非常大的尺寸。您的数组太大,无法放入您的程序堆栈。分配这样大小的一个更好的主意是在堆上分配。

#include <stdlib.h>

int *end = malloc(sizeof *end * max);

/* some stuff */

free(end);

堆比栈大很多倍。

关于c - 初始化大 vector 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13632428/

相关文章:

c - Vim 关键字补全

c - 将指针传递给函数时出现段错误

c - C 程序中的段错误(核心转储)

c++ - b2BlockAllocator.cpp 中的 Box2D 崩溃

c - 段错误(核心已转储)-找不到原因

C++二叉树递归析构函数问题

c - 使用 select 读取和写入同一个套接字(TCP)

c - 如何在 Gtree (glib) 上搜索元素?

android - 使用ndk构建错误编译具有多个c文件的 native android库 * No rule to make target

java - 使用 netbeans 定义的 GUI 在 postgreSQL 中调用位于 "postgres.c"的用户定义函数