Question on "Attaching Finalizer Functions to Values"


#1

http://dev.realworldocaml.org/garbage-collector.html

In the code example, there are nine different cases:

  attach_finalizer "immediate int" 1;
  attach_finalizer "immediate float" 1.0;
  attach_finalizer "immediate variant" (`Foo "hello");
  attach_finalizer "immediate string" "hello world";
  attach_finalizer "immediate record" { foo=false };
  attach_finalizer "allocated bool" alloced_bool;
  attach_finalizer "allocated variant" (`Foo alloced_bool);
  attach_finalizer "allocated string" alloced_string;
  attach_finalizer "allocated record" { foo=alloced_bool };

However, only six of them appears in the output:

./_build/default/finalizer.exe
       immediate int: FAIL
     immediate float: FAIL
      allocated bool: FAIL
    allocated record: OK
    allocated string: OK
   allocated variant: OK

Why is that? What happened to e.g. “immediate variant”?


#2

Fascinating. This appears to be a legit change in the behavior of the code, since running it as is does indeed generate that result in the current compiler.

I think what’s going on here is that some of these examples are misnamed. I think “immediate variant” isn’t an immediate at all; it’s just a variant that is allocated as a constant, and so is never collected. The “immediate string” example is again a constant value, not an immediate, and for the same reason is never collected. The current behavior doesn’t surprise me there, but the old one does. Maybe @avsm has a thought on this, since he wrote this example?

In any case, we should clearly update the text to explain the cases more precisely.

y


#3

Great catch! The change in collection behaviour is probably due to the shift to default-safe-string (and hence immutable strings) in recent versions of the OCaml compiler. This means that the native-code compiler is now allocating them to the RODATA section of the generated executable, which will obviously never be collected.

You can probably get the old behaviour back by playing around with the default-unsafe-string variant of the compiler in opam, but of course it’s better to fix this example (and the chapter) to explain the new immutable semantics of strings.

I’ll do this just as soon as I get some of my crazy-October lecturing in Cambridge out of the way… :slight_smile: