Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

When run the code below:[code]void F(){

  1. Jan 13, 2012 #1
    When run the code below:
    Code (Text):

    void F()

    {

      F();

    }
     
    EStackOverFlow will appear.
    The book says that there is a loop going on. Can anyone explain to me?
    Because I think in the Void F function, it will only use itself once.
     
    Last edited by a moderator: Jan 13, 2012
  2. jcsd
  3. Jan 13, 2012 #2
    Re: EStackOverFlow

    Yes, F will call again F and it will never stop. It will do this forever.
     
  4. Jan 13, 2012 #3

    Mark44

    Staff: Mentor

    Re: EStackOverFlow

    The first time F is called, right away there is a call to F. In the executable, the compiler has generated the code that is necessary to call a function. This code includes placing the return value on the stack and any parameters, and so on.

    As soon as F is entered, there's a call to F again, with more stuff being pushed on the stack.

    This process keeps repeating until you eventually run out of stack space, at which time the exception is thrown.
     
  5. Jan 13, 2012 #4
    Re: EStackOverFlow

    When ever you are using recursion make sure you have a base case to avoid stack overflows.
     
  6. Jan 13, 2012 #5
    Re: EStackOverFlow

    Code (Text):
    void f(int a){
        printf("%d\n", a-(int)&a);
        f(a);
    }

    int main() {
        int z;
        f((int)&z);
    }
     
  7. Jan 13, 2012 #6
    Re: EStackOverFlow

    The return value is returned in eax (in cdecl and stdcall). But I'm just nit picking. I'm sure you knew that, but were being general. :)
    [/quote]Right. I meant return address, but wrote return value instead.
     
    Last edited by a moderator: Jan 14, 2012
  8. Jan 14, 2012 #7

    Mark44

    Staff: Mentor

    Re: EStackOverFlow

    Right. I meant return address, but wrote return value instead.
    And if there are parameters to the function, they get pushed onto the stack as well, for some of the calling conventions, and that tends to eat up stack memory. I didn't bring this up, since the OP's function didn't take parameters.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: When run the code below:[code]void F(){
  1. Running a Fortran code (Replies: 4)

Loading...