Does GC_MALLOC actually correspond to calloc()?

398 Views Asked by At

According to the manual, GC_MALLOC clears the memory but GC_MALLOC_ATOMIC does not clear the memory.

void * GC_MALLOC(size_t nbytes)
Allocates and *clears* nbytes of storage.

void * GC_MALLOC_ATOMIC(size_t nbytes)
Allocates nbytes of storage.

https://www.hboehm.info/gc/gcinterface.html

So GC_MALLOC_ATOMIC should be used to replace malloc and GC_MALLOC should be used to replace calloc? Is it so?

1

There are 1 best solutions below

0
On

So GC_MALLOC_ATOMIC should be used to replace malloc and GC_MALLOC should be used to replace calloc? Is it so?

No.

You are correct that GC_MALLOC_ATOMIC() is like malloc() in that malloc() makes no guarantee to clear the allocated space, whereas GC_MALLOC() is like calloc() in that it does clear the allocated space, but in the most general sense, you should replace both malloc() and calloc() with GC_MALLOC(). This is because,

  1. GC_MALLOC_ATOMIC() documents this constraint:

    The client promises that the resulting object will never contain any pointers.

  2. Objects that do contain pointers must be cleared when allocated so that GC can be confident about its interpretation of those objects when it scans them for pointers.

On the other hand, one usually has some knowledge about the usage of the space one is allocating, and when one does, GC_MALLOC_ATOMIC() is to be preferred for objects that do not contain pointers. This is because GC will not (ever) spend time scanning the resulting objects for pointers. If you want the results zero-filled, then do that manually, afterward. memset() is a common means to do this.