Skip to content

Finalizer doesn't get called with ARC/ORC if it's defined on a ref ptr T type #19794

@ghost

Description

Found in https://github.com/status-im/nim-decimal via https://forum.nim-lang.org/t/9159

This code doesn't leak with refc but leaks with ARC.

I'm not sure if ARC is supposed to support finalizers like that or not, but I guess it's worth opening an issue.

Example

type
  mpd_t = object
    some, args: int

  DecimalType* = ref[ptr mpd_t]

proc deleteDecimal*(x: DecimalType) =
  echo "here"
  if not x.isNil:          # Managed by Nim
    dealloc(x[])

proc newDecimal*(): DecimalType =
  ## Initialize a empty DecimalType
  new result, deleteDecimal
  result[] = create(mpd_t)

proc main = 
  let x = newDecimal()
  echo x.some
  GC_fullCollect()

main()
GC_fullCollect()

Current Output (valgrind)

==14012== 16 bytes in 1 blocks are definitely lost in loss record 1 of 1
==14012==    at 0x484AA83: calloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==14012==    by 0x10AEA1: main__ttaa_51 (in /mnt/d/Projects/NimExperiments/tot/ttaa)
==14012==    by 0x109131: main (in /mnt/d/Projects/NimExperiments/tot/ttaa)
==14012== 
==14012== LEAK SUMMARY:
==14012==    definitely lost: 16 bytes in 1 blocks
==14012==    indirectly lost: 0 bytes in 0 blocks
==14012==      possibly lost: 0 bytes in 0 blocks
==14012==    still reachable: 0 bytes in 0 blocks
==14012==         suppressed: 0 bytes in 0 blocks

Expected Output

No leaks

Workaround

The best way would be to define a proper object and then define a destructor/finalizer on it instead of defining "weird" (in my opinion) aliases :P

Additional Information

$ nim -v
Nim Compiler Version 1.7.1 [Linux: amd64]
Compiled at 2022-05-10
Copyright (c) 2006-2022 by Andreas Rumpf

git hash: 85bc8326acc9bf18e748055e770a40890e7ac069
active boot switches: -d:release

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions