Note: This article was translated with the assistance of AI. I wrote the original in Chinese. If you can read Chinese, you are welcome to read the original Chinese version for the most authentic and unfiltered expression.

Background

I’m used to solving algorithm problems in VSCode, but often when I need to allocate large memory locally (specifically in the main function), the IDE reports Segmentation fault at runtime.

For example, the following code:

1
2
3
4
5
6
7
#include <bits/stdc++.h>
using namespace std;
int main()
{
int blocks[1001][1001]{0};
...
}

At this point, the array actually only takes up 1001 * 1001 * 8B ≈ 7.64MB of memory, yet it throws a Segmentation fault. But on the OJ, it runs fine and gets AC.

The solution is actually simple: don’t define it inside main—just make it a global variable. But in the spirit of getting to the bottom of things, I did some digging into this phenomenon.

Explanation

In C++ programs, global variables are stored on the heap, while local variables are stored on the stack. If you define a large array inside main, the limited stack space can easily cause a stack overflow, resulting in a Segmentation fault.

Then why does it work on OJ?

Actually, you can customize the upper limit of stack-allocated memory by passing arguments to the linker.

Using my VSCode configuration as an example: in the .vscode folder under your project directory, there should be a tasks.json file. Modify the configuration and add the following command to tasks.args:

1
-Wl,--stack,512000000

What this command means:

  • -Wl: tells the compiler that what follows is passed to the linker
  • --stack,512000000: sets the stack memory allocation limit to 512000000B

After the change, it should look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
{
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: g++.exe 生成活动文件",
"command": "C:\\MinGW\\bin\\g++.exe",
"args": [
"-fdiagnostics-color=always",
"-g",
"${file}",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe",
"-Wl,--stack,512000000"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "调试器生成的任务。"
}
],
"version": "2.0.0"
}

From then on, even if you allocate large memory inside main, it won’t throw an error.