【问题标题】:Memory limit in int main()int main() 中的内存限制
【发布时间】:2020-01-10 17:10:23
【问题描述】:

我需要在一项任务中制作一个大数组(超过 10^7)。

我发现如果我在 int main 中执行此操作,代码将无法正常工作(程序将在执行 cout“进程返回 -1073741571 (0xC00000FD)”之前退出)。

如果我在外面做,一切都会奏效。

(我正在使用 Code::Blocks 17.12)

// dont work
#include <bits/stdc++.h>
using namespace std;

const int N = 1e7;

int main() {
    int a[N];
    cout << 1;
    return 0;
}

// will work
#include <bits/stdc++.h>
using namespace std;

const int N = 1e7;
int a[N];

int main() {
    cout << 1;
    return 0;
}

所以我有问题:

-为什么会这样?

-如何在 int main() 中定义数组? (实际上,如果我在 int main() 中使用相同大小的向量,一切都会正常工作,这很奇怪)

【问题讨论】:

标签: c++ memory memory-limit


【解决方案1】:

问题是您的数组实际上非常大。假设 int 是 4 个字节,10 000 000 个整数将是 40 000 000 个字节,大约为 40 Mb。在 Windows 中,最大堆栈大小为 1Mb,在现代 Linux 上为 8Mb。由于局部变量位于堆栈中,因此您将 40mb 数组分配到 1mb 或 8mb 堆栈中(如果您分别在 windows 或 linux 中)。所以你的程序用完了堆栈空间。如果是全局数组,则可以,因为全局变量位于程序的 bss(data) 段中,该段具有静态大小并且不会改变。在 std::vector 的情况下,您的数组分配在动态内存中,例如在堆中,这就是你的程序没有崩溃的原因。如果您不想使用 std::vector ,您可以在堆上动态分配一个数组,如下所示

int* arrayPtr = new int[N]

然后你需要使用删除操作符释放未使用的动态分配内存:

delete arrayPtr;

但在这种情况下,您需要知道如何使用指针。或者,如果您希望它不是动态的并且仅在 main 中,您可以像这样将您的数组设为 main 静态(我认为 99.9% 这会起作用?,我认为您需要尝试)

int main() {static int arr[N];return 0;}

将位于数据段中(如全局变量)

【讨论】:

    【解决方案2】:

    有四种主要类型的内存是 C++ 程序员感兴趣的:stackheapstatic memorymemory of registers

    const int N = 1e7;
    
    int main(){int a[N];}
    

    stack 内存已部署。

    这种类型的内存在大小上通常比heapstatic memory 更受限制。 因此,返回错误代码。

    需要运算符new(或在heap中分配内存的其他函数)才能使用heap

    const int N = 1e7;
    int main(){int* a = new int[N]; delete a;}
    

    通常不会显式使用运算符new

    std::vector 使用heap(即它使用new 或下面的较低级别)(与std::arrayC-style array 相对,例如int[N])。 正因为如此,std::vector 通常能够保存比std::arrayC-style array 更大的数据块。

    如果你这样做

    const int N = 1e7;
    int a[N];
    
    int main(){}
    

    static memory 被使用。 它的大小通常比stack 内存少。

    最后,您在int main(){int a[N];} 中使用了stack,在int a[N]; int main(){} 中使用了static memory,在int main(){std::vector&lt;int&gt; v(N);} 中使用了heap,因此得到了不同的结果。

    对大数组使用heap(通过std::vector 或运算符new,上面给出了示例)。

    【讨论】:

      猜你喜欢
      • 2014-07-19
      • 2016-07-24
      • 2010-10-12
      • 2016-01-05
      • 2012-03-10
      • 2020-03-01
      • 2017-03-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多