C++ 爆 malloc异常

P1009 [NOIP1998 普及组] 阶乘之和

raysun007 @ 2023-02-19 00:06:13

C++ 程序逻辑基本是没有问题的,但是在n >= 19 时会出现如下异常

**malloc: Incorrect checksum for freed object 0x7fe08b0040f0: probably modified after being freed. Corrupt value: 0xf0000000ffd70a3e luogu(16034,0x7ff84ea4a4c0) malloc: * set a breakpoint in malloc_error_break to debug

感觉是vector使用的问题,有同学可以帮忙解答一下嘛,谢谢

#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>

using namespace std;

void split(int a, vector<int>& v) {
  while (a > 0) {
    int e = a % 10;
    a /= 10;
    v.push_back(e);
  }
}

void multiple(vector<int>& v1, int num) {
  vector<int> v2;
  split(num, v2);

  vector<int> v3(v1.size() + v2.size() + 2);

  for (int i = 1; i <= v1.size(); i++) {
    for (int j = 1; j <= v2.size(); j++) {
      v3[i + j - 1] += v1[i - 1] * v2[j - 1];
    }
  }

  // 处理进位
  for (int i = 1; i <= v1.size() + v2.size(); i++) {
    v3[i + 1] += v3[i] / 10;
    v3[i] %= 10;
  }

  int i = v3.size() - 1;
  while (i >= 0) {
    if (v3[i] > 0) {
      break;
    }
    i--;
  }
  v1.assign(v3.begin() + 1, v3.begin() + i + 1);
}

void add(vector<int>& s1, vector<int>& s2) {
  int len = std::max(s1.size(), s2.size());
  vector<int> s3(len + 2);
  for (int i = 1; i <= len + 1; i++) {
    s3[i] += s1[i - 1] + s2[i - 1];
    s3[i + 1] = s3[i] / 10;
    s3[i] %= 10;
  }
  s1.assign(s3.begin() + 1, s3[len + 1] > 0 ? s3.end() : s3.end() - 1);
}

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

  // 累加
  vector<int> s;
  s.push_back(1);

  // 累乘
  vector<int> v;
  v.push_back(1);
  for (int i = 2; i <= n; i++) {
    multiple(v, i);
    add(s, v);
  }

  for (int i = s.size() - 1; i >= 0; i--) {
    cout << s[i];
  }

  return 0;
}

by ud2_ @ 2023-02-19 02:46:13

add 函数里的这两行有错。

// s1 和 s2 不一定有 i 位数,s1[i - 1] 和 s2[i - 1] 可能越界
s3[i] += s1[i - 1] + s2[i - 1];
// i == len + 1 时 s3[i + 1] 必越界
s3[i + 1] = s3[i] / 10;

|