为什么在Windows上会RE

P3374 【模板】树状数组 1

您好,程序发生运行时错误可能有各种各样的原因,鉴于你是在本地测试,建议首先定位错误发生的代码位置。如果没有修改栈大小的话,可能是爆栈出错。
by only_a_speaker @ 2023-11-01 10:31:00


@[only_a_speaker](/user/1154375) 鹅,改的是main第二行,但是main第一行还没跑就直接RE了
by 0x28202e202e29 @ 2023-11-01 10:37:24


把 `a = BIT(n);` 移到 `main()` 外,写成 `BIT a(5e5 + 5);` 即可。
by 0x282e202e2029 @ 2023-11-01 10:39:58


兜售模板 ```cpp template<class T> inline T lowbit(T x) { return x & (-x); } template<class T> class BIT { int size; T *arr; public: BIT(int n) { size = n, arr = new T[n + 3]; memset(arr, 0, sizeof(int) * (n + 2)); } ~BIT() { delete []arr; } void modify(int pos, T value) { while (pos <= size) { arr[pos] += value, pos += lowbit(pos); } } T query(int pos) { T res = 0; while (pos) { res += arr[pos], pos -= lowbit(pos); } return res; } }; ``` 定义方法 ```cpp BIT<long long> bit(5e5); ```
by 0x282e202e2029 @ 2023-11-01 10:43:13


@[FeiWuLiuZiao](/user/790188) 您好,你说的就是我推断爆栈的原因。
by only_a_speaker @ 2023-11-01 12:06:07


@[only_a_speaker](/user/1154375) 哪里爆的,没懂
by 0x28202e202e29 @ 2023-11-01 12:41:40


@[FeiWuLiuZiao](/user/790188) 您好,在代码二中,你建立了一个临时的 `BIT` ,然后把临时的 `BIT` 赋给全局变量 `a` 上。这个临时的 `BIT` 是开在栈上的,如果没有特殊设置的话,可能会超过栈的大小限制。
by only_a_speaker @ 2023-11-01 14:27:07


@[only_a_speaker](/user/1154375) 可是如果我在第二行爆栈的话,为什么第一行都跑不出来,是编译选项有`-static`的原因?
by 0x28202e202e29 @ 2023-11-01 14:30:17


@[FeiWuLiuZiao](/user/790188) 您好, `BIT` 的大小是在编译期就确定的,你可以通过 `sizeof(BIT)` 在编译期查看其所占字节数。因此, `main` 函数需要占用的栈空间在编译期就已确定,在进入 `main` 函数入口时就会出现错误。 在 `windows` 环境上,可以通过 `-Wl,--stack=100000` 编译指令指定栈空间的大小。
by only_a_speaker @ 2023-11-01 14:35:10


@[only_a_speaker](/user/1154375) 收到,谢谢
by 0x28202e202e29 @ 2023-11-01 14:36:09


|