开启o2优化全部WA,不开全AC???

P1009 [NOIP1998 普及组] 阶乘之和

gbz123 @ 2024-07-15 17:38:55

如题,开启o2优化后提示第一行第一列是p,但是我自己用vs测试没有这种问题,此外不开反而AC了

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstdio>
#include<cstring>
#include<stdlib.h>
using namespace std;
char a[60][5000]={0}, len[5000],temp[5000];
int main() {
    int i,jw=0,n,j=0,t;
    a[1][0] = 1;
    len[1] = 1;
    for (i = 2; i <= 50; i++) {
        jw = 0;
        j = 4999;
        while (j >= 0) {
            if (a[i-1][j] != 0) {
                break;
            }
            j--;
        }
        len[i-1] = j+1;
        j = 0;
        while (j<len[i-1] + 2) {
            t = a[i - 1][j] * i+jw;
            jw = t / 10;
            a[i][j] = t % 10;
            j++;
        }
        if (jw) {
            t = a[i - 1][j] * i + jw;
            jw = t / 10;
            a[i][j] = t % 10;
        }
    }
    j = 4999;
    while (a[50][j] == 0) {
        j--;
    }
    len[50] = j;
    scanf("%d", &n);
    temp[0] = 1;
    jw = 0;
    int p;
    for (i = 2; i <= n; i++) {
        for (j = 0; j <= len[i];j++) {
            t = temp[j] + a[i][j]+jw;
            jw = t / 10;
            temp[j] = t % 10;
        }
        while (jw) {
            t = temp[j] + a[i][j] + jw;
            jw = t / 10;
            temp[j] = t % 10;
            j++;
        }

    }
    if (n != 1) {
        p = 5999;

        while (temp[p] == 0) {
            p--;
        }
        for (int k = p; k >= 0; k--) {
            cout << (char)(temp[k] + 48);
        }
    }
    else {
        cout << 1;
    }
}

by __szh_DNCB__ @ 2024-07-15 17:39:45

@gbz123 厌氧代码吧


by nr0728 @ 2024-07-15 17:56:07

你用 g++ main.cpp -o main -O2 -fsanitize=address,undefined 编译并运行试试


by gbz123 @ 2024-07-15 18:05:58

@nr0728 原来是越界了,记错一开始temp数组的大小了,谢谢佬


by gbz123 @ 2024-07-15 18:06:27

@szh_DNCB 发现是越界了,我紫菜


|