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

使用long变量时出现Segmentation Fault (11)错误,求代码修正

Troubleshooting Your C++ Segmentation Fault (11)

Hey there! Let's break down why you're hitting that segmentation fault and fix it up. Looking at your code snippet, there are two key issues that are almost certainly causing the crash:

1. Fixed-Size Arrays Can't Handle Large N Values

Your sAni and tAni arrays are declared with a fixed size of 1000:

long sAni[1000], tAni[1000];

But if the input value of N is greater than 1000, your loop for (long i = 0; i < N; i++) will write past the end of these arrays. This out-of-bounds access triggers undefined behavior—one common result is a segmentation fault.

2. Variable-Length Arrays Cause Stack Overflow

The line:

bool occupied[L+1] = {};

uses a variable-length array (VLA), which isn't part of standard C++ (it's a non-portable GCC extension). Even worse, if L is a large number (like 100,000 or more), allocating this array on the stack will overflow the stack's limited memory (usually only a few megabytes). Stack overflow is a frequent culprit behind segmentation faults.


Fixed Code

Here's a corrected version using standard C++ features to eliminate both issues:

#include <iostream>
#include <vector>
using namespace std;

int main () {
    long L, N;
    cin >> L;
    cin >> N;

    // Dynamically size these vectors to match input N
    vector<long> sAni(N);
    vector<long> tAni(N);

    // Heap-allocated vector avoids stack overflow, even for large L
    vector<bool> occupied(L + 1, false);

    for (long i = 0; i < N; i++) {
        cin >> sAni[i] >> tAni[i];
    }

    for (long i = 0; i < N; i++) {
        for (long j = sAni[i]; j <= tAni[i]; j++) {
            occupied[j] = true;
        }
    }

    // Finish the count calculation your code cut off
    long count = 0;
    for (bool isOccupied : occupied) {
        if (isOccupied) count++;
    }

    cout << "Total occupied positions: " << count << endl;
    return 0;
}

Key Fixes:

  • Replaced fixed-size arrays with vector<long> initialized to size N, so they always match the number of intervals you're inputting.
  • Swapped the VLA occupied with a vector<bool>, which allocates memory on the heap instead of the stack—safe even for large values of L.
  • Added the missing count calculation and output to complete the logical flow of your code.

内容的提问来源于stack exchange,提问作者Grayson Ho

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:08:11