使用long变量时出现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 sizeN, so they always match the number of intervals you're inputting. - Swapped the VLA
occupiedwith avector<bool>, which allocates memory on the heap instead of the stack—safe even for large values ofL. - Added the missing count calculation and output to complete the logical flow of your code.
内容的提问来源于stack exchange,提问作者Grayson Ho

