Home > Articles > Programming > C/C++

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Allocating Scanned Memory

From: gc.m

If you allocate memory with malloc(), it is invisible to the garbage collector. This is a problem if you want, for example, something like a C array containing objects. We’ve already looked at one solution to this. You can call CFRetain() on the object you are about to store and CFRelease() on the old value, and then swap them over.

This is not ideal, although it will work. The other option is to allocate a region of memory from the garbage collector. The NSAllocateCollectable() function is similar to malloc(), but with two important differences.

The first is that the memory that it returns is garbage collected. There is no corresponding NSFreeCollectable() function. When the last pointer to the buffer disappears, the buffer will be collected.

The second difference is that the second parameter to this function defines the kind of memory that you want. If you are going to be using the buffer for storing C types, you can just pass zero here. If you pass NSScannedOption, the returned buffer will be scanned as a possible location of object pointers, as well as pointers to other memory regions returned by NSAllocateCollectable().

  • + Share This
  • 🔖 Save To Your Account