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

前端 未结 12 1622
情歌与酒
情歌与酒 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条回答
  •  Happy的楠姐
    2020-12-12 20:54

    malloc and free go hand in hand, with each "malloc" being matched by one "free". Thus it makes total sense that the "free" matching a previous "malloc" should simply free up the amount of memory allocated by that malloc - this is the majority use case that would make sense in 99% of cases. Imagine all the memory errors if all uses of malloc/free by all programmers around the world ever, would need the programmer to keep track of the amount allocated in malloc, and then remember to free the same. The scenario you talk about should really be using multiple mallocs/frees in some kind of memory management implementation.

提交回复
热议问题