11

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?

ThisSuitIsBlackNot
  • 23,492
  • 9
  • 63
  • 110
yoniyes
  • 1,000
  • 11
  • 23
  • 6
    http://www.perlmonks.org/?node_id=1159029 can help – Dada Sep 22 '16 at 21:28
  • In Perl, if you don't create any circular dependencies (ie. references to things that point back at themselves) that you manually purge, everything is cleaned up (automatic garbage collection) when the current scope exits. The final scope is the script file itself. – stevieb Sep 22 '16 at 22:31
  • 4
    all that said, I'd recommend structuring code in a way that doesn't need `goto` (it's pretty easy). If in a loop, we have `next` and `last`. – stevieb Sep 22 '16 at 22:34
  • @stevieb I'm not intending to use `goto` in my code, just wondering :) But what if we have a label and we `goto` it inside the same scope and in between we declare a variable? That's a bit unclear to me – yoniyes Sep 22 '16 at 22:37
  • capiche. Just putting it out there for others :) ++ on the question. – stevieb Sep 22 '16 at 22:40

1 Answers1

2

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.

elcaro
  • 2,227
  • 13
  • 15
  • 9
    not a leak, since perl doesn't lose track of the memory, and will free it all at scope exit. – ysth Sep 23 '16 at 02:02
  • just to make sure I got this, in your example, Perl will still track all the `my $x`s for each `goto` and in this case, will eventually fill all the available memory? – yoniyes Sep 24 '16 at 19:24
  • yonyon100: it seems so, yes. I only ran the first example for about 1 minute, and memory use continued to climb. – elcaro Sep 25 '16 at 20:05