Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gc:arc memory leak when using "return" keyword #13627

Closed
khchen opened this issue Mar 11, 2020 · 3 comments
Closed

gc:arc memory leak when using "return" keyword #13627

khchen opened this issue Mar 11, 2020 · 3 comments

Comments

@khchen
Copy link
Contributor

khchen commented Mar 11, 2020

I found a memory leak when using system.find(). It seems to be caused by "return" keyword.

Example

type
  Foo = ref object of RootObj
    data: int
    children*: seq[Foo]

proc `=destroy`(self: var type(Foo()[])) =
  echo "destroy foo ", self.data
  for i in self.fields: i.reset

# Just a copy of system.find.
proc systemFind[T, S](a: T, item: S): int {.inline.}=
  for i in items(a):
    if i == item: return
    inc(result)
  result = -1

# Another version without "return" keyword.
proc myFind[T, S](a: T, item: S): int {.inline.}=
  var found = false
  for i in items(a):
    if i == item:
      found = true
      break
    inc(result)

  if not found:
    result = -1

var w1 = Foo(data: 1)
var w2 = Foo(data: 2)
var w3 = Foo(data: 3)

w1.children = @[w2, w3]
discard w1.children.systemFind(w3) # Has memory leak
# discard w1.children.myFind(w3) # No memory leak

Current Output

destroy foo 1
destroy foo 2

Expected Output

destroy foo 1
destroy foo 2
destroy foo 3
$ nim -v
Nim Compiler Version 1.1.1 [Windows: amd64]
Compiled at 2020-03-11
@cooldome
Copy link
Member

Works with cpp, so I believe it is goto exceptions related

@cooldome
Copy link
Member

Tested: c with setjmp works too

@Araq
Copy link
Member

Araq commented Mar 12, 2020

It's caused by the try finally optimization.

Araq added a commit that referenced this issue Mar 12, 2020
@Araq Araq closed this as completed in a6682de Mar 12, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants