求助: C++ 数组越界不报错问题

P1591 阶乘数码

raysun007 @ 2023-02-24 00:36:36

求助: C++数组越界

已通过本题,但是使用初版程序(如下)运行时, 当输入为1000 0时,编译器未爆数组下标越界错误,请教luogu的各位同学解答一下

#include<iostream>
#include<cmath>
#include<cstdio>
#include<algorithm>
#include<string>
#include<set>
#include<unordered_set>
#include<vector>
#include<climits>
#include<limits>
#include<map>
#include<unordered_map>
#include<string.h>

using namespace std;

int arr[500];
int lenArr = 0;

void multiple(int* array, int len, string num) {
  reverse(num.begin(), num.end());

  int lenT = len + num.size();
  int temp[lenT + 1];
  memset(temp, 0, sizeof(temp));
  for (int i = 0; i < len; i++) {
    for (int j = 0; j < num.size(); j++) {
      temp[i + j] += array[i] * (num[j] - '0');
    }
  }

  memset(arr, 0, sizeof(arr));
  for (int k = 0; k < lenT; k++) {
    temp[k + 1] += temp[k] / 10;
    temp[k] %= 10;
    arr[k] = temp[k];
  }

  lenArr = lenT;
}

int main() {
  int t;
  cin >> t;

  int input[t][2];
  for (int i = 0; i < t; i++) {
    cin >> input[i][0] >> input[i][1];
  }

  for (int i = 0; i < t; i++) {
    memset(arr, 0, sizeof(arr));

    int n = input[i][0];
    int a = input[i][1];

    arr[0] = 1;
    lenArr = 1;
    for (int k = 2; k <= n; k++) {
      multiple(arr, lenArr, to_string(k));
    }

    int m = lenArr;
    while (arr[m] == 0) {
      m--;
    }

    int cnt = 0;
    for (int i = 0; i <= m; i++) {
      if (arr[i] == a) {
        cnt++;
      }
    }
    cout << cnt << endl;
  }

  return 0;
}

by CPPZhengHuoRen @ 2023-02-24 05:34:32

@raysun007 用visual studio(模式选择debug)就可以检测数组越界了, 不过建议放在堆区

int *arr = new int [500];

用完了再从堆区删掉

delete arr;

by You_Quiet @ 2023-02-24 11:28:40

@raysun007 DEV的话,不会报错,但在运行的时候会爆,好像是


by CSP_AK_xyy20110721 @ 2023-02-24 12:01:03

@raysun007 我刚交了一下,现在是RE


by raysun007 @ 2023-02-25 23:17:37

@xyy20110721 是的,luogu提交是会RE,但由于是MacOS,所以用的是VSCode + lldb,所以,感觉是编译器的问题,所以向其他同学了解下用其他编译器是否也不会报错


by CSP_AK_xyy20110721 @ 2023-02-27 12:46:52

没错,数组越界在本地的编译器看来是合法使用数组,不信你在运行下这段代码

#include<stdio.h>
int main()
{
    int i;//栈
    int arr[10];
    for(i=0;i<=10;i++)
    {
        arr[i] = 0;
        printf("%d\n",i);
    }
}

|