Search code examples
perlmemorygoto

Can `goto LABEL` cause a memory leak?


Can using goto with labels cause memory leaks? All I found in the documentation for goto that seems relevant is:

The goto LABEL form finds the statement labeled with LABEL and resumes execution there.

Is it safe to use goto LABEL?


Solution

  • After 1 minute of testing, the answer seems to be: yes no (see update below)

    Watching top while this is running, %MEM continually increments

    {
        THIS:
        my $x = 1;
        goto THIS;
    }
    

    This does not exhibit the same incrementing %MEM counter

    while (1) {
        my $x = 1;
    }
    

    UPDATE

    I misunderstood the question. My take on the question was whether memory would be allocated for a lexical variable that already existed in that lexical scope with the use of a goto, and my test seems to say yes. Strictly speaking, this is not a memory leak. Should perl ever exit this lexical scope, the allocated space would be released.