Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error main: malloc.c:2401: sysmalloc: Assertion Doing a simple C++ fibonacci assignment

I am working on this assignment and i trying to figure this out. When i input any other numbers between 1 to 10 except 6. The fibonacci_fast(n) outputs an error main: malloc.c:2401: sysmalloc: Assertion. However, when i use an array to replace the vector or just uncomment the std::cout. It will work fine. Can anyone enlighten me what’s the error that i have made.


#include <iostream>
#include <cassert>
#include <vector>
#include <algorithm>



int fibonacci_naive(int n) {
        if (n <= 1)
        return n;

    return fibonacci_naive(n - 1) + fibonacci_naive(n - 2);
    
}

int fibonacci_fast(int n) {

    std::vector<int> numbers{0,n};
    numbers[0] =0;
    numbers[1] =1;
    int ans=0;
    if (n <= 1)
    {
        return n;
    }
    
        //std::cout<<std::endl;
        //int numbers[n];

        for(int i=2;i<=n;i++)
        {
            numbers[i] = numbers[i-1] + numbers[i-2];
            
        }

        ans = numbers[n];

        return ans;
    

    
}

void test_solution() {
    assert(fibonacci_fast(3) == 2);
    assert(fibonacci_fast(10) == 55);
    for (int n = 0; n < 20; ++n)
        assert(fibonacci_fast(n) == fibonacci_naive(n));
}

int main() {
    int n = 0;
    std::cin >> n;

    //std::cout << fibonacci_naive(n) << '\n';
    //test_solution();
    std::cout << fibonacci_fast(n) << std::endl;
    return 0;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

std::vector<int> numbers{0,n}; creates a vector of size 2, not of size n. You probably want to use std::vector<int> numbers(n, 0).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading