【问题标题】:C++ terminate called after throwing an instance of 'std::bad_alloc'抛出“std::bad_alloc”的实例后调用 C++ 终止
【发布时间】:2017-12-27 05:23:43
【问题描述】:

给定一个整数,我们需要找到整数的超位。

我们使用以下规则定义整数x 的超级数字:

如果x只有1个数字,那么它的超级数字是x 否则, 的上位等于x 的数字和的上位。这里,一个数字的数字和定义为它的数字之和。

例子:

super_digit(9875) = super_digit(9+8+7+5) 

= super_digit(29) 

= super_digit(2+9)

= super_digit(11)

= super_digit(1+1)

= super_digit(2)

= 2

任务: 你有两个数字n 和k。您必须计算p.p 的超级数字是在数字n 连接k 次时创建的。

我解决这个问题的代码如下所示。

#include <bits/stdc++.h>
#include <string>
#include <iostream>
#include <math.h>

using namespace std;

int superDigit(string n, int k)
{
    int res=0;
    for (int x = 0; x < n.length(); x++)
    {
        res += n[x] - '0';
    }
    res = k * res;
    if (res < 10)
        return res;
    else
        return superDigit(to_string(res),1);
}

int main() {
    string n;
    int k;
    cin >> n;
    cin >> k;
    cout << superDigit(n, k)<< endl;
    return 0;
}

代码似乎对所有小数字都正常工作,但是当n 是1e100000-1 和k 是100000,程序返回如下错误:

在抛出 'std::bad_alloc' 的实例后调用终止

what(): std::bad_alloc

我认为这是内存泄漏,但我该如何解决。泄漏发生在哪里?

【问题讨论】:

  • 不是因为内存泄漏。它无法分配指定数量的内存。更多信息可以在这里找到:en.cppreference.com/w/cpp/memory/new/bad_alloc
  • 使用调试器。它将在引发异常的点停止。非常有用。
  • 很高兴知道这一点,但我该如何解决这个问题。
  • 第一件事可能是消除递归。
  • 无关:看来你不知道#include &lt;bits/stdc++.h&gt; 做了什么,所以我建议在Why should I not #include &lt;bits/stdc++.h&gt;? 变成坏习惯之前先阅读一下。

标签: c++ recursion memory-leaks


【解决方案1】:

您将n 视为1e10000-1。这大约是1e10000 个字符长。假设每个字符大约是1 字节大小。那么,

1e10000 bytes = 1e9997 kilobytes = 1e9994 MB = 1e9994 GB = 1e9991 TB 如您所见,它非常大。

【讨论】:

  • Re "大约 1e10000 个字符长。"考虑到该规范的源代码必须有多大,假设 OP 将其直接放在那里,如所示。有什么让你觉得值得注意的地方吗?
  • 我修复了代码(见上文),但我得到了错误的结果-194313216。
  • 这是1e100000,而不是1e10000
  • @Follj:以后,请不要在发布答案后从根本上改变问题。幸好这个答案是错误的。但如果这是一个很好的答案,你只会让它无效,否定那个人的工作。
  • @Cheersandhth.-Alf 我会记住这一点的。对不起,我是新来的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多