Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

This programs takes a long time to close after the 'return;' on main()

This is the code I am dealing with:

#include <iostream>
#include <map>

using namespace std;

static unsigned long collatzLength(unsigned long n) {
    static std::map<unsigned long,int> collatzMap;
    int mapResult = collatzMap[n];
    if (mapResult != 0) return mapResult;

    if (n == 1) {
        return 1;
    } else { 
        collatzMap[n] = 1 + collatzLength(n%2==0?n/2:3*n+1);
        return collatzMap[n];
    }
}

int main() {
    int maxIndex = 1;
    unsigned int max = 1;
    for (int i=1; i<1000000; i++) {
        //cout<<i<<endl;
        unsigned long count = collatzLength(i);
        if (count > max) {
            maxIndex = i;
            max = count;
        }
    }
    cout<<maxIndex<<endl;
    getchar();
    cout<<"Returning..."<<endl;
    return maxIndex;
}

When I compile and run this program (using Visual Studio 2012 and Release build settings) it takes like 10 seconds (on my computer) to close after the program prints "Returning..."

Why is that?

Note: I am aware that this program is bad written and that i probably shouldn't be using 'static' on the collatzLength nor using a cache for that function, but I am not interesting on how to make this code better, I am just interesting about why does it take so much to close.

like image 403
José D. Avatar asked Aug 20 '13 15:08

José D.


People also ask

How do I stop a program from running in C++?

In C++, you can exit a program in these ways: Call the exit function. Call the abort function. Execute a return statement from main .

What is the return 0 in C++?

return 0: A return 0 means that the program will execute successfully and did what it was intended to do. return 1: A return 1 means that there is some error while executing the program, and it is not performing what it was intended to do.

Does return exit the function?

A return statement ends the execution of a function, and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call. A return statement can return a value to the calling function.

What does the return function do in C++?

return Statement (C++)Terminates the execution of a function and returns control to the calling function (or to the operating system if you transfer control from the main function). Execution resumes in the calling function at the point immediately following the call.


1 Answers

Go to project settings on your start up project, Debugging section. Enter _NO_DEBUG_HEAP=1 into the Environment section. You need to do this even in Release mode.

like image 79
Neil Kirk Avatar answered Sep 21 '22 09:09

Neil Kirk