Why does `free` in C not take the number of bytes to be freed?

前端 未结 12 1638
情歌与酒
情歌与酒 2020-12-12 20:11

Just to be clear: I do know that malloc and free are implemented in the C library, which usually allocates chunks of memory from the OS and does it

12条回答
  •  长情又很酷
    2020-12-12 20:55

    Why does free in C not take the number of bytes to be freed?

    Because it doesn't need to. The information is already available in the internal management performed by malloc/free.

    Here are two considerations (that may or may not have contributed to this decision):

    • Why would you expect a function to receive a parameter it doesn't need?

      (this would complicate virtually all client code relying on dynamic memory, and add completely unnecessary redundancy to your application). Keeping track of pointer allocation is already a dificult problem. Keeping track of memory allocations along with associated sizes would increase the complexity of client code unnecessarily.

    • What would the altered free function do, in these cases?

      void * p = malloc(20);
      free(p, 25); // (1) wrong size provided by client code
      free(NULL, 10); // (2) generic argument mismatch
      

      Would it not free (cause a memory leak?)? Ignore the second parameter? Stop the application by calling exit? Implementing this would add extra failure points in your application, for a feature you probably don't need (and if you need it, see my last point, below - "implementing solution at application level").

    Rather, I want to know why free was made this way in the first place.

    Because this is the "proper" way to do it. An API should require the arguments it needs to perform it's operation, and no more than that.

    It also occurs to me that explicitly giving the number of bytes to free might allow for some performance optimisations, e.g. an allocator that has separate pools for different allocation sizes would be able to determine which pool to free from just by looking at the input arguments, and there would be less space overhead overall.

    The proper ways to implement that, are:

    • (at the system level) within the implementation of malloc - there is nothing stopping the library implementer from writing malloc to use various strategies internally, based on received size.

    • (at application level) by wrapping malloc and free within your own APIs, and using those instead (everywhere in your application that you may need).

提交回复
热议问题