GC.calloc(), then what?
safety0ff via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Jun 27 00:34:54 PDT 2014
On Friday, 27 June 2014 at 07:03:28 UTC, Ali Çehreli wrote:
> 1) After allocating memory by GC.calloc() to place objects on
> it, what else should one do?
Use std.conv.emplace.
> In what situations does one need to call addRoot() or
> addRange()?
Add root creates an internal reference within the GC to the
memory pointed by the argument (void* p.)
This pins the memory so that it won't be collected by the GC.
E.g. you're going to pass a string to an extern C function, and
the function will store a pointer to the string within its own
data structures. Since the GC won't have access to the data
structures, you must addRoot it to avoid creating a dangling
pointer in the C data structure.
Add range is usually for cases when you use
stdc.stdlib.malloc/calloc and place pointers to GC managed memory
within that memory. This allows the GC to scan that memory for
pointers during collection, otherwise it may reclaim memory which
is pointed to my malloc'd memory.
> 2) Does the answer to the previous question differ for struct
> objects versus class objects?
No.
> 3) Is there a difference between core.stdc.stdlib.calloc() and
> GC.calloc() in that regard? Which one to use in what situation?
One is GC managed, the other is not. calloc simply means the
memory is pre-zero'd, it has nothing to do with "C allocation" /
"allocation in the C language"
> 4) Are the random bit patterns in a malloc()'ed memory always a
> concern for false pointers? Does that become a concern after
> calling addRoot() or addRange()?
If by malloc you're talking about stdc.stdlib.malloc then:
It only becomes a concern after you call addRange, and the false
pointers potential is only present within the range you gave to
addRange.
So if you over-allocate using malloc and give the entire memory
range to addRange, then any false pointers in the un-intialized
portion become a concern.
If you're talking about GC.malloc():
Currently the GC zeros the memory unless you allocate NO_SCAN
memory, so it only differs in the NO_SCAN case.
> If so, why would anyone ever malloc() instead of always
> calloc()'ing?
To save on redundant zero'ing.
More information about the Digitalmars-d-learn
mailing list