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

Weird IDE memory error while trying to compile

#include <iostream>

int collatz(int num);

int main() 
{
    std::cout << "test case: " << collatz(13) << std::endl;
    std::cout << "dinosaurs: " << collatz(66054000) << std::endl;
}

int collatz(int num) 
{
    int counter = 0;

    do {
        if (num % 2 == 0) {
            collatz(num / 2);
            counter++;
        }
        else
            collatz(num * 3 + 1);
            counter++;
    } while (num > 1);

    return counter;
}

This is my code, I’m getting an error like this when trying to compile: Unhandled exception at 0x00007FF7D2113559 in LAB 5 CISC 360 2.exe: 0xC00000FD: Stack overflow (parameters: 0x0000000000000001, 0x0000003E76663F98).

I tried to change the data types of all the stuff involved with the function collatz() but i don’t think the issue is data types, its me not understanding how the memory is being used in this function. Plz help.

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

>Solution :

This is not a compilation error, its an abort of your program. Its failing becuase you are calling the same function recursively too many times.

int main() 
{
    std::cout << "test case: " << collatz(13) << std::endl;
    std::cout << "dinosaurs: " << collatz(66054000) << std::endl; <<<====
}

int collatz(int num) 
{
    int counter = 0;

    do {
        if (num % 2 == 0) {
            collatz(num / 2); <<=====
            counter++;
        }
        else
            collatz(num * 3 + 1); <<<<<=====
            counter++;
    } while (num > 1);

    return counter;
}

Your code calls collatz, which calls collatz etc. This eats up stack space which is a limited resource, typically in the range of 1 MB or so. Depending on how much each call does you can get a few thousand calls deep before the OS gives up.

You 13 case will have worked, but not that huge number

Not clear what you are trying to do but you will have to redesign your algorithm

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