Will using goto cause memory leaks?

前端 未结 10 2051
迷失自我
迷失自我 2021-01-17 11:33

I have a program in which i need to break out of a large bunch of nested for loops. So far, the way most people have been telling me to do it is to use an ugly goto in my co

相关标签:
10条回答
  • 2021-01-17 12:03

    No, any automatic variables in your loops will not cause programming leaks if you break out of your loops with a goto statement.

    0 讨论(0)
  • 2021-01-17 12:09

    Will backward goto leak resources ? Or any other potential problems with below code ?

    Reexecute:

            try
            {
                //Setup request
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    
                ....
    
                //Get Response
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    
               if(response != HttpStatus.OK && noOfRetries < 3)
                {
                    noOfRetries++;
                    Thread.Sleep(10 * 1000);
    
    
                    response.Close();
                    goto Reexecute;
                }
                ...
    
                response.Close();
             }
             catch
             {
    
             }
    
    0 讨论(0)
  • 2021-01-17 12:11

    Goto is not always bad, but in your case you probably shouldn't be using goto.

    See examples of good use of goto here and here.

    If you goto a label that is outside of scope your object on the stack will be freed.

    Example:

    #include <iostream>
    using namespace std;
    
    class A
    {
    public:
      ~A() 
      {
         cout<<"A destructor"<<endl;
      }
    };
    
    
    
    int main(int argc, char**argv)
    {
      {
        A a;
        cout<<"Inside scope"<<endl;
        goto l;
        cout<<"After l goto"<<endl;
      }
    
      cout<<"Outside of scope before l label"<<endl;
    
    l:
      cout<<"After l label"<<endl;
      return 0;
    }
    

    This will print:

    Inside scope
    A destructor
    After l label

    0 讨论(0)
  • 2021-01-17 12:16

    No. You can only leak memory that is dynamically allocated.

    0 讨论(0)
  • 2021-01-17 12:21

    Stack variables are defined (and allocated) the moment you enter the function, and are implicitly eliminated the moment you leave the function (since the entire call stack record is popped away). No amount of bouncing around inside the function can possibly cause any havoc with memory that's been allocated the whole time. Regardless of what execution path you take through the code, the stack record will pop when control returns to the calling function, and the memory will be freed.

    0 讨论(0)
  • 2021-01-17 12:21

    No you will not.

    However, make sure that any external resources are properly released. For example, if you opened a file it would be possible to jump past where it would normally be closed.

    0 讨论(0)
提交回复
热议问题