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 |
|
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 to512000000B
After the change, it should look like this:
1 | { |
From then on, even if you allocate large memory inside main, it won’t throw an error.