You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

栈溢出报错求助:本地C++编译失败但在线编译器可正常运行

Why You're Getting a Stack Overflow & How to Fix It

Hey there, let's break down why that stack overflow error is plaguing you and how to fix it quickly.

The Root Cause

When you declare arrays like int input[500][500]; and int sum[505][505]; inside a function (as local variables), they get allocated on the call stack—a small, limited memory region (usually only a few megabytes, depending on your compiler/OS). Let's do the math:

  • Each int is typically 4 bytes.
  • input[500][500] uses 500 * 500 * 4 = 1,000,000 bytes (~1MB).
  • sum[505][505] uses 505 * 505 * 4 = 1,020,100 bytes (~1MB).

Together, these two arrays take up over 2MB of stack space. If your local compiler's stack limit is lower than that (which is common for desktop compilers like MSVC), you'll hit the 0xC00000FD: Stack overflow error right away.

Online compilers often have more generous stack limits or use different memory handling under the hood, which is why your code works there but fails locally.

Fixes to Try

Here are three straightforward solutions, ordered by how recommended they are:

  • Use std::vector for dynamic heap allocation
    This is the most portable and C++-idiomatic approach. Vectors allocate memory on the heap (which has way more space than the stack) and manage it automatically:

    int N;
    cin >> N;
    vector<vector<int>> input(500, vector<int>(500));
    vector<vector<int>> sum(505, vector<int>(505));
    
  • Declare the arrays as global variables
    Global variables live in the global data segment (not the stack), so they don't count against your stack limit. Just move the declarations outside of any function:

    int input[500][500];
    int sum[505][505];
    
    int main() {
        int N;
        cin >> N;
        // rest of your code
    }
    

    Note: Be cautious with global variables in larger programs—they can lead to unintended side effects.

  • Increase the stack size in your compiler settings
    If you really want to keep using local arrays, you can adjust your compiler's stack limit. For example, in Visual Studio, you'd go to Project Properties > Linker > System > Stack Reserve Size and set a larger value (like 4MB or more). However, this isn't portable—it won't work across different compilers or OSes, so it's not ideal for most cases.

内容的提问来源于stack exchange,提问作者Antonio SEO

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:30:00