1

Getting an error Getting Error : terminate called after throwing an instance of std::bad_alloc what(): std::bad_alloc

#include <iostream>
#include <inttypes.h>

using namespace std;

int64_t fibonacci(int64_t n,int64_t m) {
    int64_t *fibarray = new int64_t[n];
    for(int64_t i=0; i<n; i++)
    {
        if(i<=1)
            fibarray[i]=i;
        else
            fibarray[i]=(fibarray[i-1]+fibarray[i-2])%1000;
    }
    int64_t rett = (fibarray[n-1]%m);
    delete []fibarray;
    return rett;
}

int main() {
    int64_t n=0,m=0;
    cin>>n>>m;
    cout<<fibonacci(n+1,m);
}

Why std::bad_alloc has been thrown in this case?

i am calculating it for 2816213588

mrflash818
  • 930
  • 13
  • 24
yash jain
  • 60
  • 9

1 Answers1

1

As others have already pointed out, it's likely a problem with n being too large.

try replacing

int64_t *fibarray = new int64_t[n];

with

int64_t *fibarray = new(nothrow) int64_t[n];
if (fibarray == nullptr) return -1; // now check for null

Check for null before even entering the loop. This is good practice especially since you expose the values of n and m to the user without any limits or checks for validity.

Quadir Ali
  • 126
  • 1
  • 4
  • My program is being stuck.. i am not getting any error but it is stuck... I am running it for 2816213588 – yash jain Jun 01 '18 at 15:38
  • 1
    also with a number that large, you are going to experience some overflow especially trying to store it into another int64. For example, just adding the last 2 numbers alone from that sequence and you're already outside of the range of uint64! You can change your return value to a double and/or limit that n value to something that is within your max range. I would recommend the latter. – Quadir Ali Jun 01 '18 at 16:14
  • As a side note, consider for a second how much memory is being used by that one fibarray. Let's assume you're running on hardware where an int64_t occupies 8 bytes of memory. 8 * 2816213588 = 22529708704 bytes. Thats about 21 GIGABYTES of ram for a single variable! Sometimes these things can't be avoided, but as already mentioned by Paul, this isn't one of those cases. You only need to keep track of the previous 2 fib values to calculate the current one – Quadir Ali Jun 01 '18 at 19:16