Re: [m-users.] MR_GC_free ?
Peter Wang <[email protected]> Wed, 8 Nov 2023 12:15:01 +1100
| Newsgroups | gmane.comp.lang.mercury.general |
|---|---|
| Message-ID | <[email protected]> |
On Tue, 07 Nov 2023 20:17:06 +0100 Volker Wysk <[email protected]> wrote: > Hi > > Am Mittwoch, dem 08.11.2023 um 05:53 +1100 schrieb Zoltan Somogyi: > > On 2023-11-08 05:48 +11:00 AEDT, "Volker Wysk" <[email protected]> wrote: > > > Hi. > > > > > > In the ODBC library, there's space allocated by MR_GC_NEW and explicitly > > > freed with MR_GC_free. This confuses me. Shouldn't space allocated by > > > MR_CG_NEW be deallocated by the garbage collector? If it is to be > > > deallocated explicitly, shouldn't the space be allocated by MR_NEW and be > > > deallocated by MR_free? > > > > Follow the definition of MR_GC_free in runtime/mercury_memory.h > > to boehm_gc/include/gc.h. > > This leads to this (I couldn't understand the definition of this function): > > /* Explicitly deallocate an object. Dangerous if used incorrectly. */ > /* Requires a pointer to the base of an object. */ > /* An object should not be enabled for finalization (and it should not */ > /* contain registered disappearing links of any kind) when it is */ > /* explicitly deallocated. */ > /* GC_free(0) is a no-op, as required by ANSI C for free. */ > GC_API void GC_CALL GC_free(void *); > > So the gc explicitly frees the object and remembers that it has done so, so > it won't be garbage collected later. > > Is it bad style to use MR_GC_NEW and MR_GC_free, since it should rather be > done with MR_NEW/MR_free? (That's what those are there for, aren't they?) They do different things. MR_GC_NEW allocates memory that will be garbage collected when there are no more references to it (as far as the GC can see). MR_GC_free deallocates the memory immediately, before a GC cycle, even if there might actually be references to it hanging around. Rarely, there MAY be performance advantages to doing so, e.g. if you allocate a large object and definitely don't need it any more, and don't want to wait for one or more GC cycles for that memory to be reclaimed. MR_NEW is just a wrapper around the C library's malloc routine. The GC doesn't see inside inside malloc-allocated memory. You should generally not use MR_NEW or any variant of malloc to allocate memory for an object that may contain pointers to GC-allocated memory. If the last reference(s) to a GC-allocated object only exist within memory allocated by malloc then, as far as the GC is concerned, that GC-allocated object is no longer referenced and may be reclaimed. In a Mercury program, you'll want to allocate GC-able memory unless there is a specific reason not to. Peter _______________________________________________ users mailing list [email protected] https://lists.mercurylang.org/listinfo/users