栈溢出报错求助:本地C++编译失败但在线编译器可正常运行
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
intis typically 4 bytes. input[500][500]uses500 * 500 * 4 = 1,000,000bytes (~1MB).sum[505][505]uses505 * 505 * 4 = 1,020,100bytes (~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::vectorfor 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

