0

Possible Duplicate:
What is a stack overflow error?

look the code below.

#include <iostream>
using namespace std;

void leave(double as){
    cout<<as;
    leave(as);
}


int main(){
    double x=1234.5;
    leave(x);
    cout<<"hellow";
}

When this code executes their is no way to stop. it should print the value x over and over again. But practically, this works for about 20 secs and close automatically. It doesn't print the line hellow. What is the reason for it? In windows task manager I can realize that the memory used with the application will increase. but I have allocated memory for x within the main function only, so will the function allocate memory for x over and over again. Is this type of situation called a memory leak? if its so what lines should be added to prevent it?

If I change the code as below it shows the word hellow without going through the function over and over again:

 void leave(){
     leave();
  }

  int main(){
      leave();
      cout<<"hellow";
  }

How to explain these situations?

Community
  • 1
  • 1
danial weaber
  • 846
  • 2
  • 17
  • 37
  • 1
    Your answer is [stack overflow](http://stackoverflow.com/questions/214741/what-is-a-stack-overflow-error). – Shahbaz Dec 05 '12 at 17:00
  • 1
    It is not a memory leak it is a stack increase. Eventually you will have your application closed by the ssytem. More here: http://support.microsoft.com/kb/100775 – joy Dec 05 '12 at 17:09
  • 1
    That doesn't explain why the second one works, though. Is the compiler optimizing out the `leave()` function because it doesn't do anything? – Barmar Dec 05 '12 at 17:10
  • 1
    nothing is added on stack in the second example. Also if you compile the first example with fastcall, or on 64 bit you should experience another behaviour. – joy Dec 05 '12 at 17:12
  • +1 for all answers. all helped me to get an idea in. – danial weaber Dec 05 '12 at 17:16
  • can someone tell me what is a meomary leack, explain with a small example. will a meomary leack also increase the meomary used automatically. – danial weaber Dec 05 '12 at 17:19
  • memory leak is any time you allocate memory without deallocating (a new without a delete). The OS will clean up all memory when the program exists so its just a 'memory leak' while the process is running. – g19fanatic Dec 05 '12 at 17:37

1 Answers1

1

Every call to leave() results in adding a little information to the stack. When you call it recursively, the stack grows until it runs out of space, and the operating system terminates the application. In the second example, presumably the compiler optimized out the function that did nothing.

mark
  • 5,269
  • 2
  • 21
  • 34