2020-12-01 16:29

Custom memory allocation

I think I finally cracked the nut on custom memory allocation. Back in the ~0.3 versions, libcork had custom memory allocation, but it was very invasive: you had to pass around lots of cork_alloc pointers all over the place. I dropped custom allocators to make the memory allocation API much cleaner (and much closer to the standard malloc family of functions).

This patch adds back in the ability to customize the details of how memory is allocated, but without requiring lots of allocator pointers — and most importantly, in a way that lets different sections of the program have different custom allocators. The key is the cork_current_allocator macro, and in how all of the allocation functions are defined static in a header file. That allows different source files to provide different values for cork_current_allocator, which their copy of the static allocation functions will use.

There are two breaking changes. The first is that you must now use cork_free, cork_cfree, or cork_delete to free memory that you've allocated, instead of the standard free function. The second is that you must keep track of how large each allocation is, and pass that in to whichever free function you use.


  • 点赞
  • 回答
  • 收藏
  • 复制链接分享